c - 分配动态结构数组

标签 c arrays malloc dynamic-allocation

我正在尝试使用包含动态数组的结构的动态数组。 分配在函数 build_resuts 中完成,内存在函数 free_data 中释放。

我这样做正确吗?

typedef struct InputResultsLine 
{
    long registered;
    long *candidates;
} InputResultsLine;

void func()
{
    InputResultsLine *data, totals;
    int nbPollingPlaces = 10;

    build_results(&data, &totals,  5, nbPollingPlaces);     

    free_data(&data, &totals, nbPollingPlaces); 
}

void build_results(InputResultsLine **data, InputResultsLine *totals, int nbCandidates, int nbPollingPlaces)
{   
    int i;
    InputResultsLine *ptrCurrentLine;

    totals->candidates = (long*) malloc(nbCandidates * sizeof(long));       

    *data = (InputResultsLine*) malloc(nbPollingPlaces * sizeof(InputResultsLine));

    for(i = 0; i < nbPollingPlaces; i++)
    {       
        ptrCurrentLine = &((*data)[i]);
        ptrCurrentLine->candidates = (long*) malloc(nbCandidates * sizeof(long));

        // [...]    
    }   
}

void free_data(InputResultsLine **data, InputResultsLine *totals, int nbPollingPlaces)
{
    int i;  

    for(i = 0; i < nbPollingPlaces; i++)
    {
        free(((*data)[i]).candidates);
    }

    free(totals->candidates);
    free(*data);
}

我看到分配的样本是这样的:

*data = (InputResultsLine*) malloc(nbPollingPlaces * (sizeof(InputResultsLine) + nbCandidates * sizeof(long)));

所以我不确定我应该怎么做以及为什么:

最佳答案

(顺便说一句,在 C 中,您不需要强制转换 malloc() 的返回值:如果没有强制转换就无法编译,那么您就犯了一个错误)

你觉得奇怪的代码涉及在单个缓冲区中分配所有数组:这允许更好的“内存局部性”(即相关的东西一起在内存中),但不能单独修改数组:这对性能有好处但仅对初始化一次且不随时间变化(或至少其大小不随时间变化)的数据有用。

它还允许你只调用一次 free() 就可以释放整个东西,并使错误处理更简单(因为你不必检查所有的 malloc() 循环中的调用成功,如果没有,则释放到目前为止已经成功的所有调用,而不是其他...)

关于c - 分配动态结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628961/

相关文章:

arrays - CGGetOnlineDisplayList在Swift中的使用(数组作为参数)

javascript - 为什么我不能在 JavaScript 中做 array[-1]?

c - 使用 malloc() 进行多个输入?

c - 为什么我的程序返回相同的字符?

c - errno 97 aka EAFNOSUPPORT aka 协议(protocol)不支持的地址族的可能原因

C 套接字接收 : connection reset by peer

php - 检查一个数组是否有一个或多个空值

c++ - 如何在 MAC OS c/c++ 中阻止 USB 存储设备

c - 断言在某个点失败

c - 我在函数中分配内存,并返回 char*,我应该如何释放它?