This is the code I wrote to take the values of a matrix and display it
#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);
}
}
}
The program is getting stuck at the loop in displayMatrix
, but it displays fine if I remove the outer for loop.
The error I get is Segmentation fault (core dumped)
.
What am I doing wrong?
PS: I have to use the above function signature with double pointers.