2013-08-12 2 views
-1

다음은 다차원 배열을 재 할당 할 때의 코드입니다. add_line 함수를 한 번 이상 사용하면 코드가 작동하지 않습니다. 하루 종일 알아 내려고 노력했다. 누군가 도울 수 있습니까? 여기에 코드의 고정 된 (그러나 검증되지 않은) 버전 -다차원 배열 재 할당

void add_line(char ** wlist, char * word, int * size) // Extending wordlist or cross 
{ 
    (*size)++; 
    char ** new_wlist = (char**)realloc(wlist,(*size)*sizeof(char*)); 
    if(new_wlist == NULL) 
     show_error("Reallocation error",1); 

    wlist = new_wlist; 
    wlist[(*size)-1] = (char*)malloc(ROW_SIZE*sizeof(char)); 
    if(strlen(word)>ROW_SIZE) 
     show_error("Word too long", 1); 
    strcpy(wlist[(*size)-1],word); 
} 
int main() 
{ 
    int * w_size = (int*)malloc(sizeof(int)); 
    int * c_size = (int*)malloc(sizeof(int)); 
    *w_size = 0; 
    *c_size = 0; 
    char ** wordlist = (char**)malloc(sizeof(char*)); 
    char ** cross = (char **)malloc(sizeof(char*)); 

    add_line(cross,"test1",c_size); 
    add_line(cross,"test2",c_size); 
    return 0; 
} 
+1

'코드가 작동하지 않습니다'는 의미는 무엇입니까? – Undefined

답변

1

문제는 당신이 수정 된 wlist를 반환하지 않는 것입니다 :

void add_line(char *** wlist, const char * word, int * size) // Extending wordlist or cross 
       // ^^^ note extra level of indirection here 
{ 
    int new_size = *size + 1; 
    char ** new_wlist = realloc(*wlist, new_size*sizeof(char*)); 
    if (new_wlist == NULL) 
     show_error("Reallocation error",1); 

    new_wlist[new_size-1] = malloc(ROW_SIZE); 
    if (strlen(word)>ROW_SIZE) 
     show_error("Word too long", 1); 
    strcpy(new_wlist[new_size-1],word); 
    *wlist = new_wlist; 
    *size = new_size; 
} 

int main() 
{ 
    int c_size = 0; // NB: no need for dynamic allocation here 

    char ** cross = NULL; // NB: initial size is zero - realloc will do the right thing 

    add_line(&cross, "test1", &c_size); 
      //^pass pointer to cross here 
    add_line(&cross, "test2", &c_size); 
      //^pass pointer to cross here 

    return 0; 
} 

가 나는 또한 몇 가지 다른 사소한 문제를 해결 한을 - cross의 초기 크기는 이제 0 (1)이고 c_size에 대한 불필요한 동적 할당을 제거했습니다. 또한 C에서 잠재적으로 위험한 불필요한 캐스트를 제거하고 중복으로 sizeof(char) (정의에서 1과 동일)을 사용했습니다.