重新分配结构数组

reallocing array of structs

所以我花了几个小时试图弄清楚为什么我的 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;
}

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 在评论中指出的那样,另一种方法是 return 来自函数 enlargeFileInfosrealloced 内存:

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?, and change the signature of main to int main(void)