所以我花了几个小时试图找出为什么我的realloc没有扩大我的结构数组,但我似乎没有取得任何进展。 Realloc要么失败,要么放大阵列。我做的是否有任何明显的错误?
#include <getopt.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct fileInfo {
char accessRights[12];
short hardLinks;
short userName;
short groupName;
long size;
char *time;
char *fileName;
short nrOfNode;
} fileInfo;
void enlargeFileInfos(fileInfo *fileInfoArray, int currentSize)
{
fileInfo *temp = (fileInfo*)realloc(fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (!temp) {
printf("realloc --FAILED--\n");
return;
}
fileInfoArray = temp;
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
}
int main( )
{
size_t nrOfDirs = 1;
fileInfo *fileInfoArr = malloc(sizeof(fileInfo));
for (int i = 0; i < 5; i++) {
enlargeFileInfos(fileInfoArr, nrOfDirs);
nrOfDirs++;
}
return 0;
}
答案 0 :(得分:1)
要realloc
指向fileInfoArray
内的enlargeFileInfos
内存,您必须将其地址传递给该函数:
void enlargeFileInfos(fileInfo **fileInfoArray, int currentSize)
{
fileInfo *temp = realloc(*fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (temp == NULL) {
printf("realloc --FAILED--\n");
return;
}
*fileInfoArray = temp;
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
}
然后以这种方式调用函数:
enlargeFileInfos(&fileInfoArr, nrOfDirs);
正如评论中 Jonathan Leffler 所指出的,另一种方法是从函数realloc
返回enlargeFileInfos
ed内存:
fileInfo *enlargeFileInfos(fileInfo *fileInfoArray, int currentSize)
{
fileInfo *temp = realloc(fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (temp == NULL) {
printf("realloc --FAILED--\n");
return NULL;
}
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
return temp;
}
而且,你用这种方式:
fileInfoArr = enlargeFileInfos(fileInfoArr, nrOfDirs);
if (fileInfoArr == NULL) {
/* Handle allocation failure */
}
使用fileInfoArr
后,请不要忘记释放它:
free(fileInfoArr);
我已从realloc
移除了演员,因此请查看Do I cast the result of malloc?,并将main
的签名更改为int main(void)
。