2016-11-16 3 views
1

동적 배열을 포함하는 구조체의 동적 배열을 사용하려고합니다. 할당은 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

+0

먼저 valgrind와 같은 메모리 디버거를 실행 해보십시오. –

답변

0

를 (C에서 당신은하지 않습니다 malloc()의 반환 값을 캐스팅해야합니다. 캐스트없이 컴파일하지 않으면 실수를 한 것입니다.

이상한 코드는 al 모든 배열을 단일 버퍼에 배치 : 더 나은 "메모리 지역"(즉, 관련된 것들을 메모리에 함께 저장). 개별적으로 배열을 수정할 수없는 대가를 치러야합니다. 성능은 좋지만 한 번 초기화되고 시간이 지남에 따라 변경되지 않는 데이터 (또는 적어도 시간이 지남에 따라 크기가 변하지 않는 데이터)에 유용합니다).

또한 free()을 한 번만 호출하여 모든 것을 해제 할 수 있으며 루프에서 모든 malloc() 호출이 성공했는지 확인하지 않아도되므로 오류 처리가 훨씬 쉬워집니다. 그렇지 않은 경우 모든 통화를 무료로 사용하십시오 지금까지 성공한 것이지 다른 것 ...)