2014-04-18 30 views
0

getTable將結構的二維數組的內容取出,並將存儲在 中的int複製到table。但是,當我嘗試從中的table中讀取任何內容時,運行時出現Segmentation fault錯誤。修改函數中的2D malloc數組C

void getTable(char*s1, char*s2, char**table) 
{ 
/* 
SKIP SOME STUFF 
*/ 

    table = malloc(sizeof(char*)*(s2Len+1)); 
    for (i = 0 ; i <= s2Len; i++) 
     table[i] = malloc(sizeof(char)*(s1Len+1)); 
    for (i = 0 ; i <= s2Len; i++) 
     for (j = 0 ; j <= s1Len; j++) 
      table[i][j] = '0' + tmpTable[i][j].num; 

//prints what table points to correctly 
    for (i = 0 ; i <= s2Len; i++) 
    { 
     printf("\n"); 
     for (j = 0 ; j <= s1Len; j++) 
      printf("%2c", table[i][j]); 
    } 
    printf("\n"); 
} 

int main(void) 
{ 

    char ** table; // for number table 

/* 
SKIP SOME STUFF 
*/ 

// gives error: Segmentation fault (core dumped) 
    getTable(s1,s2,table); 
    printf("getTable test\n"); 
    int i, j; 
    // 
    for (i = 0 ; i <= strlen(s2); i++) 
    { 
     printf("\n"); 
     for (j = 0 ; j <= strlen(s1); j++) 
      printf("%c ", table[i][j]); 
    } 
    return 0; 
} 
+0

在getTable()調用之前和之後打印指針表的值。它改變了嗎? – this

+0

也許嘗試爲主表分配內存?所以把table = malloc(sizeof(char *)*(s2Len + 1));就在getTable之前。 – redFur

回答

0

試試這個:

void getTable(char*s1, char*s2, char***pTable) 
{ 
    char **table = *pTable; 
    .... rest of code ... 
} 

,並在主:

int main(void) 
{ 
    char ** table; // for number table 
    getTable(s1,s2, &table); 
    ... rest of code ... 
} 

在原代碼,您爲表參數分配內存,但在主要的本地表沒有得到這個值,所以你需要將本地地址傳遞給你的函數。 另一種方法是使你的getTable功能在主返回**,你可以分配給本地表:

char **getTable(char*s1, char*s2) 
{ 
    char **table; 
    .... rest of code ... 
    return table; 
} 

int main(void) 
{ 
    char **table; 

    table = getTable(s1,s2); 
    ... rest of code ... 
} 
1

你修改的子功能(getTable),但我不一個局部變量(表)看不到你把它傳回給調用者的位置。我認爲調用者(主)仍在查看其原始值表。

如果您在調用函數後將表的main的值初始化爲NULL,並用%p的printf值表示值,我認爲它仍然會指向NULL。