我已經做了一個庫程序來存儲電影和使用動態內存分配我的結構數組沒有成功。添加第一個記錄(電影)可以正常工作,但在第二個記錄之後,這些值只是混亂的字符。realloc函數內數組的結構
沒有什麼比說明我的代碼真的多。
的問題是,我不能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'。 – fritzone
在變量輸入完成後,我正在增加'records' – Zn3