【发布时间】:2013-10-27 17:38:05
【问题描述】:
我制作了一个库程序来存储电影,并为我的结构数组使用动态内存分配,但没有成功。添加第一条记录(电影)可以正常工作,但在第二条之后,值只是混乱的字符。
除了展示我的代码之外,没什么好说的了。
问题是我不能在我的函数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;
}
【问题讨论】:
-
您不需要在 C 程序中强制转换
malloc或realloc的返回值。 -
你应该在你的代码中增加
records。 -
我在变量输入完成后递增
records -
我收到错误:请求成员“”不是结构或联合。
fgets(*movie[index].name, 40, stdin);*movie[index].id = input_number(&movie[index].id);
标签: c dynamic struct malloc realloc