我想在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
您將'result'初始化爲10個char **元素的數組。然後你用'char *'指針填充這個數組的前3個元素,剩下的7個設置爲零。您的運行時錯誤發生在下面的嵌套循環中,在這裏您取消引用所有這些空指針並嘗試在其中存儲文本字符串。 – 2014-10-02 20:27:13
你說得對,@squeamishossifrage。我顛倒了這個概念。我很感謝你。現在所有的工作。 – 2014-10-02 20:35:20