我试图用 C 语言获取 char * 矩阵,但出现运行时错误。以下代码显示了我如何尝试执行此操作。谁能告诉我哪里错了以及为什么?我是 C 编程新手,但我来自 Java 和 PHP 世界。 预先感谢您的关注和帮助
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:我正在使用带有 C99 的 xCode
此处发生运行时错误:
result[i][j] = (char *)malloc(100 * sizeof(char));
xCode 返回 EXC_BAD_ACCESS
最佳答案
这个:
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)
如果您的平台支持 VLA,您可以通过利用 VLA 来消除分配循环之一。如果完成,代码将减少为使用单个 calloc
分配整个 char*
矩阵。例如:
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");
}
}
关于c - 如何获得 char * 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26168969/