Realloc an array of Structs

半世苍凉 提交于 2020-01-02 09:54:27

问题


I am trying to dynamically reallocate memory for an array of structs (actually an array each of 2 structs but 1 included here for simplicity) that is being read from/to a file or inputted by the user.

typedef Struct
{
    char surname[21];
    char firstname[21];
    char username[21];
...
} User;

...in main():

int size = 0; /* stores no. of structs */
User* user_array = (User *) calloc(1, sizeof(User));
if(user_array == NULL)
{
    printf("Cannot allocate initial memory for data\n");
    exit(1);
}
else
    size++;

I am then trying to use a function call to increase the array when needed:

int growArray(User user_array*, int size)
{
    User *temp;
    size++;
    temp = (User *) realloc(user_array, (size * sizeof(User));
    if(temp == NULL)
    {
        printf("Cannot allocate more memory.\n");
        exit(1);
    }
    else
        user_array = temp;
    return size;
}

Unfortunately the realloc never works. Both structs are only about 200 bytes per instance and setting the initial size to say 10 will work fine, so there must be something wrong with the way I am trying to use realloc.

System is Win 7 64, on Core i5 with 4GB, running Quincy (a MinGW GUI).


回答1:


You're changing the value of user_array locally. The value is lost when the function returns. Pass a pointer to the user_array pointer instead.




回答2:


realloc changes the size of the memory pointed to by user_array to the specified size, it doesn't increase it by size. Seeing as your function is called growArray, i'd presume you want it to increase the size of the array by size, in which case you need to:

int growArray(User **user_array, int currentSize, int numNewElems)
{
    const int totalSize = currentSize + numNewElems;
    User *temp = (User*)realloc(*user_array, (totalSize * sizeof(User)));

    if (temp == NULL)
    {
        printf("Cannot allocate more memory.\n");
        return 0;
    }
    else
    {
        *user_array = temp;
    }

    return totalSize;
}

Note that growArray takes the address of user_array, the reason for this is that realloc might move the memory if it couldn't extend the existing block to the required size.

To use it:

int size = 0;
User* user_array = (User *) calloc(1, sizeof(User));
if(user_array == NULL)
{
    printf("Cannot allocate initial memory for data\n");
    exit(1);
}

/* add 10 new elements to the array */
size = growArray(&user_array, size, 10);


来源:https://stackoverflow.com/questions/6169972/realloc-an-array-of-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!