我想在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