동적 배열을 포함하는 구조체의 동적 배열을 사용하려고합니다. 할당은 build_resuts 함수에서 수행되고 메모리는 free_data 함수에서 해제됩니다.동적 구조 배열을 할당하십시오.
제대로하고 있습니까? 나는 내가 할 방법을 잘 모르겠어요 그래서
*data = (InputResultsLine*) malloc(nbPollingPlaces * (sizeof(InputResultsLine) + nbCandidates * sizeof(long)));
이유 :
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);
}
내가 할당 같았다 샘플을보고, BTW
먼저 valgrind와 같은 메모리 디버거를 실행 해보십시오. –