the*_*337 2 c arrays struct realloc
我正在尝试为一个结构数组(实际上是一个数组,每个包含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)
不幸的是,realloc永远不会有效.这两个结构只有每个实例大约200个字节,并且将初始大小设置为10可以正常工作,因此我尝试使用realloc的方式一定有问题.
系统是Win 7 64,在Core i5上运行4GB,运行Quincy(MinGW GUI).
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22466 次 |
| 最近记录: |