0

I have made a library program to store movies in and using dynamic memory allocation for my struct array without success. Adding the first record (movie) works fine, but after the second the values are just messed up characters.

There is not really much more to say than showing my code.

The problem is that I can't realloc inside my function addmovie();

But if I put this line:

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

Right before calling addmovie(); function it seems to work, why?

/* 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;
}
4

1 回答 1

3

C 是一种按值传递的语言。当你这样做时:

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

在您的功能中,moviefrommain()完全不受影响。您需要传递一个指向指针的指针:

void addmovie(struct movies **movie)

然后修改指针的内容:

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

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

查看comp.lang.c FAQ 问题 4.8以获得完整的解释。

于 2013-10-18T18:56:35.850 回答