【发布时间】:2017-03-30 11:08:29
【问题描述】:
我正在尝试使用包含动态数组的结构的动态数组。 分配在函数 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)));
所以我不确定我应该怎么做以及为什么:
【问题讨论】:
-
先尝试运行像 valgrind 这样的内存调试器。
标签: c arrays malloc dynamic-allocation