我正在尝试为从文件读取或向文件读取或由用户输入的结构数组(实际上是 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;
}
不幸的是,重新分配永远不会起作用。这两个结构体每个实例只有大约 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;
}
注意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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)