重新分配结构体数组
我正在尝试为从文件读取或向文件读取或由用户输入的结构数组(实际上是 2 个结构体中的每一个,但为了简单起见,此处包含 1 个结构体)动态重新分配内存。
typedef Struct
{
char surname[21];
char firstname[21];
char username[21];
...
} User;
...在 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++;
然后,我尝试在需要时使用函数调用来增加数组:
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,Core i5,4GB,运行 Quincy(MinGW GUI)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
realloc
将user_array
指向的内存大小更改为指定大小,但不会增加大小。鉴于您的函数名为growArray
,我假设您希望它将数组的大小增加size
,在这种情况下您需要:请注意
growArray
获取user_array
的地址,原因是realloc
如果无法将现有块扩展到所需的大小,可能会移动内存。使用方法:
realloc
changes the size of the memory pointed to byuser_array
to the specified size, it doesn't increase it by size. Seeing as your function is calledgrowArray
, i'd presume you want it to increase the size of the array bysize
, in which case you need to:Note that
growArray
takes the address ofuser_array
, the reason for this is thatrealloc
might move the memory if it couldn't extend the existing block to the required size.To use it:
您正在本地更改 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.