<分区>
这是我编写的代码,用于获取矩阵的值并显示它
#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:我必须使用带有双指针的上述函数签名。