2014-10-02 54 views
0

我想在C語言中獲得一個char *矩陣,但運行時錯誤發生在我身上。以下代碼顯示了我如何嘗試這樣做。誰能告訴我我錯在哪裏,爲什麼?我是C編程新手,但我來自Java和PHP世界。 預先感謝您有興趣,並幫助我如何獲得char *矩陣?

int rows = 10; 
int cols = 3; 

//I create rows 
char *** result = calloc(rows, sizeof(char **)); 

//I create cols 
for (int i = 0; i < cols; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

//Load values into the matrix 
for (int i = 0; i < rows; i++) 
{ 
    for (int j = 0; j < cols; j++) 
    { 
     result[i][j] = (char *)malloc(100 * sizeof(char)); 
     if (NULL != result[i][j]) 
     { 
      strcpy(result[i][j], "hello"); 
     } 
    } 
    printf("\n"); 
} 

//Print the matrix 
for (int i = 0; i < rows; i++) 
{ 
    for (int j = 0; j < cols; j++) 
    { 
     printf("%s\t", result[i][j]); 
    } 
    printf("\n"); 
} 

PS:我使用的Xcode與C99

運行時錯誤發生在這裏:

result[i][j] = (char *)malloc(100 * sizeof(char)); 

的Xcode returs我EXC_BAD_ACCESS

+0

您將'result'初始化爲10個char **元素的數組。然後你用'char *'指針填充這個數組的前3個元素,剩下的7個設置爲零。您的運行時錯誤發生在下面的嵌套循環中,在這裏您取消引用所有這些空指針並嘗試在其中存儲文本字符串。 – 2014-10-02 20:27:13

+0

你說得對,@squeamishossifrage。我顛倒了這個概念。我很感謝你。現在所有的工作。 – 2014-10-02 20:35:20

回答

1

此:

for (int i = 0; i < cols; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

應該是這樣的:

// -----------------here 
for (int i = 0; i < rows; i++) 
{ 
    result[i] = calloc(cols, sizeof(char *)); 
} 

無關:Stop casting memory allocation functions in C。這:

result[i][j] = (char*)malloc(100 * sizeof(char)); 

應該僅僅是這樣的:

result[i][j] = malloc(100 * sizeof(char)); 

我覺得很奇怪,這是在這裏,因爲你沒有正確不calloc結果。


替代版本:可變長度的數組(VLA)

您可以通過利用VLAS如果你的平臺支持它們切出你的分配環中的一個。如果完成,代碼將減少到分配char*的整個矩陣與一個單一的calloc。例如:

int main() 
{ 
    int rows = 10; 
    int cols = 3; 

    // create rows 
    char *(*result)[cols] = calloc(rows, sizeof(*result)); 

    // load values into the matrix 
    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      result[i][j] = malloc(100 * sizeof(char)); 
      if (NULL != result[i][j]) 
      { 
       strcpy(result[i][j], "hello"); 
      } 
     } 
     printf("\n"); 
    } 

    //Print the matrix 
    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      printf("%s\t", result[i][j]); 
     } 
     printf("\n"); 
    } 
} 
+0

我試過你的解決方案和所有的工作。正如我對@squeamishossifrage所說的,我顛倒了這個概念。我非常感謝你。祝你有個愉快的夜晚:)) – 2014-10-02 20:37:40

0

在第一個for循環中,您只爲3行分配內存,並且您試圖訪問最後一個循環中的3行以上。