【发布时间】:2017-06-07 05:27:13
【问题描述】:
这是我编写的用于获取矩阵值并显示它的代码
#include<stdio.h>
int ** readMatrix(int rows, int cols)
{
int i,j, matrix[rows*cols];
int *b[rows];
int **y=b;
int k=0;
for(k=0; k < rows; k++)
{
b[k]=&matrix[k*cols];
}
for(i=0; i< rows*cols; i++)
{
scanf("%d", matrix+i);
}
return y;
}
void displayMatrix(int **a, int rows, int cols)
{
int k=0,j;
for(k=0; k < rows; k++)
{
for(j=0; j < cols; j++)
{
printf("%d ", *(*(a + k) + j));
}
printf("\n");
}
}
int main()
{
int rows,cols;
printf("Enter the number of rows:\n");
scanf("%d",&rows);
if(rows <= 0)
{
printf("Invalid Input");
}
else
{
printf("Enter the number of columns:\n");
scanf("%d",&cols);
if(cols <= 0)
{
printf("Invalid Input");
}
else
{
printf("Enter the values:\n");
int **a = readMatrix(rows, cols);
displayMatrix(a, rows, cols);
}
}
}
程序卡在displayMatrix 的循环中,但如果我删除外部 for 循环,它会显示正常。
我得到的错误是Segmentation fault (core dumped)。
我做错了什么?
PS:我必须使用带有双指针的上述函数签名。
【问题讨论】:
-
matrix是readMatrix的局部变量,因此它的生命周期仅限于该函数的范围。 -
请注意,您的代码中任何地方都没有二维数组。
matrix是一维 VLA,而您传递的其他变量是指向指针的指针。 -
在您的
diaplayMatrix函数中,您可以使用a[k][j]而不是*(*(a + k) + j)。他们做同样的事情,但第一个更容易阅读。我还建议使用变量名i和j而不是k和j,只是为了约定俗成。