영화를 저장하고 구조체 배열에 동적 메모리 할당을 사용하는 라이브러리 프로그램을 만들었습니다. 첫 번째 레코드 (동영상) 추가 잘 작동하지만 두 번째 값을 그냥 엉망진 된 문자가 있습니다.배열 내부 함수의 realloc 구조체
내 코드를 보여주는 것보다 훨씬 더 말할 것도 없습니다.
문제는 그 내가 할 수없는 realloc
내 기능 addmovie();
내부하지만이 줄을 세우면 : 작동하는 것 같다 addmovie();
함수를 호출하기 전에
movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies));
오른쪽, 왜?
/* 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