我制作了一个库程序,用于在我的struct数组中存储电影并使用动态内存分配,但没有成功。添加第一个记录(电影)工作正常,但在第二个记录之后,值只是混乱的字符。
除了展示我的代码之外,没有什么可说的。
问题是我无法在realloc
addmovie();
但是,如果我把这一行:
movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies));
在调用addmovie();
函数之前,它似乎有效,为什么?
/* Global variables */
int records = 0; // Number of records
struct movies{
char name[40];
int id;
};
addmovie(struct movies **movie)
{
int done = 1;
char again;
int index;
while (done)
{
index = records;
records++; // Increment total of records
struct movies *tmp = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies));
if (tmp)
*movie = tmp;
system("cls");
fflush(stdin);
printf("Enter name of the Movie: ");
fgets(movie[index].name, 40, stdin);
fflush(stdin);
printf("Enter itemnumber of the Movie: ");
scanf("%d", &movie[index].id);
printf("\nSuccessfully added Movie record!\n");
printf("\nDo you want to add another Movie? (Y/N) ");
do
{
again = getch();
} while ( (again != 'y') && (again != 'n') );
switch ( again )
{
case ('y'):
break;
case ('n'):
done = 0;
break;
}
} // While
}
int main()
{
int choice;
struct movies *movie;
movie = (struct movies *) malloc(sizeof(struct movies)); // Dynamic memory, 68byte which is size of struct
while (done)
{
system("cls");
fflush(stdin);
choice = menu(); //returns value from menu
switch (choice)
{
case 1:
addmovie(movie);
break;
}
} // While
free(movie); // Free allocated memory
return 0;
}
答案 0 :(得分:3)
C是一种按值传递的语言。当你这样做时:
movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies));
在您的功能中,来自movie
的{{1}}完全不受影响。你需要传递一个指向指针的指针:
main()
然后修改指针的内容:
void addmovie(struct movies **movie)
请注意,不要将struct movies *tmp = realloc(...)
if (tmp)
*movies = tmp;
的返回值分配给要传递给它的变量也很重要 - 最终可能会泄漏。
查看comp.lang.c FAQ question 4.8以获取完整说明。