gpt4 book ai didi

c - 在函数内部重新分配数组结构

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:27 24 4
gpt4 key购买 nike

我已经制作了一个库程序来存储电影并为我的结构数组使用动态内存分配但没有成功。添加第一条记录(电影)工作正常,但在第二条之后,值只是乱七八糟的字符。

除了展示我的代码,没有什么可说的了。

问题是我不能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 是一种按值传递的语言。当你这样做时:

movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies));

在您的函数中,main() 中的movie 完全不受影响。您需要传递一个指向指针的指针:

void addmovie(struct movies **movie)

然后修改指针的内容:

struct movies *tmp = realloc(...)
if (tmp)
*movies = tmp;

请注意,不要将 realloc 的返回值分配回要传递给它的变量,这一点也很重要 - 您可能最终会泄漏。

检查 comp.lang.c FAQ question 4.8以获得完整的解释。

关于c - 在函数内部重新分配数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com