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

标签 c dynamic struct malloc 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 是一种按值传递的语言。当你这样做时:

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/

相关文章:

python - 动态创建子类的类型注解

java - 有没有更优雅的方式来启动基于列表的线程?

c - malloc 灾难性地失败

c - 在c中访问数组的-1元素

将字符串元素与 ASCII 值进行比较

c - 我无法在 Windows 7 上设置服务器来监听特定端口

c - 如何正确使用 ExAllocatePoolWithTag 使其不返回 STATUS_INSUFFICIENT_RESOURCES?

c - C : examples? 中的正则表达式

java - 我可以将函数名称存储在最终的 HashMap 中以供执行吗?

c - 数组作为结构的一部分