Here in this code I am trying to dynamically allocate memory to a 2d array and print it The problem I face here is I cant get the output properly lets assume my input is an 2d array of size 2*2 [1,2,3,4] but the output printed is [1,1,1,1].
#include <stdio.h>
#include <stdlib.h>
int output_func(int row, int col, int *ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
printf(" %d ", *ptr);
}
printf("|\n");
}
}
int main()
{
int **ptr;
int row, col;
int i, j;
printf("enter the no of rows for the matrix: ");
scanf("%d", &row);
printf("enter the no of col for the matrix: ");
scanf("%d", &col);
ptr = (int **)malloc(row * sizeof(int *));
for (int i = 0; i < row; i++)
{
ptr[i] = (int *)malloc(col * sizeof(int));
}
// input of first matrix
printf("\nEnter the elements for first matrix :\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("\t A[%d,%d] = ", i, j);
scanf("%d", &ptr[i][j]);
}
}
output_func(row, col, *ptr);
return 0;
}
output_funccan't access to the superior dimension (because there isn't one, because you never provided one). The second hint is the call inmain, which purposely dereferences theptrvar to comply with the inappropriateoutput_funcdeclaration. While that allows the code to compile, compile-success does not mean it is correct.printf(" %d ", *ptr);scanf("%d", &ptr[i][j]);and the other hasprintf(" %d ", *ptr);. Can you justify the difference?