小编the*_*337的帖子

重新分配一组Structs

我正在尝试为一个结构数组(实际上是一个数组,每个包含2个结构,但为了简单起见,这里包括1个)来动态重新分配内存,这些结构正在从文件中读取或由用户输入.

typedef Struct
{
    char surname[21];
    char firstname[21];
    char username[21];
...
} User;
Run Code Online (Sandbox Code Playgroud)

...在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++;
Run Code Online (Sandbox Code Playgroud)

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

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;
} …
Run Code Online (Sandbox Code Playgroud)

c arrays struct realloc

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

arrays ×1

c ×1

realloc ×1

struct ×1