重新分配结构数组 [英] Realloc an array of Structs
问题描述
我正在尝试为从文件中读取或输入到用户或由用户输入的结构数组(实际上是2个结构,但为了简化起见在此包括1个数组)动态地重新分配内存。
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;
...在main()中:
...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;
}
不幸的是,重新分配永远都行不通,每个实例的结构都只有200字节左右,初始大小设置为10很好,所以我尝试使用realloc的方式一定存在问题。
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.
系统是Win 7 64,在具有4GB的Core i5上运行Quincy(一个MinGW GUI)。
System is Win 7 64, on Core i5 with 4GB, running Quincy (a MinGW GUI).
推荐答案
您正在本地更改user_array的值。该函数返回时该值将丢失。而是改为指向user_array指针。
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.
这篇关于重新分配结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!