4

我正在尝试为正在从文件读取/向文件读取或由用户输入的结构数组(实际上是 2 个结构中的每个数组,但为了简单起见,此处包含 1 个)动态重新分配内存。

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

...在主要()中:

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++;

然后,我尝试在需要时使用函数调用来增加数组:

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;
}

不幸的是,realloc 永远不会起作用。两个结构每个实例只有大约 200 个字节,将初始大小设置为 10 可以正常工作,所以我尝试使用 realloc 的方式一定有问题。

系统是 Win 7 64,在具有 4GB 的 Core i5 上,运行 Quincy(MinGW GUI)。

4

2 回答 2

7

realloc将指向的内存大小更改为user_array指定大小,它不会按大小增加。看到你的函数被调用growArray,我假设你希望它增加数组的大小size,在这种情况下你需要:

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;
}

请注意,它growArray采用 的地址user_array,原因是realloc如果它无法将现有块扩展到所需的大小,则可能会移动内存。

要使用它:

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);
于 2011-05-29T21:15:55.687 回答
4

您正在本地更改 user_array 的值。函数返回时该值丢失。而是将指针传递给 user_array 指针。

于 2011-05-29T19:42:10.453 回答