【问题标题】:realloc struct of array inside function函数内部数组的realloc结构
【发布时间】:2013-10-27 17:38:05
【问题描述】:

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

除了展示我的代码之外,没什么好说的了。

问题是我不能在我的函数reallocaddmovie();

但是,如果我把这行:

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 程序中强制转换 mallocrealloc 的返回值。
  • 你应该在你的代码中增加records
  • 我在变量输入完成后递增records
  • 我收到错误:请求成员“”不是结构或联合。 fgets(*movie[index].name, 40, stdin);*movie[index].id = input_number(&movie[index].id);

标签: c dynamic struct malloc realloc


【解决方案1】:

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 以获得完整说明。

【讨论】:

  • 向 OP 指出他没有检查 realloc 的返回值也可能会有所帮助,如果它失败,指向原始分配内存的指针丢失并且他遭受内存泄漏
  • 我对你的期望不会低于 :)
  • 感谢您的回答,但您能否再解释一下,第一次使用动态数组。这 tmp 是什么?
  • 您是否将tmp 设为指向*movie 的指针?我应该为我的变量使用 tmp 吗?比如说tmp[index].name
  • @Pankrates 仍然不知道我应该如何使用双指针解决方案 realloc 我的结构
猜你喜欢
  • 2017-06-08
  • 2016-05-16
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
相关资源
最近更新 更多