I am using the below code snippet to allocate memory for 2D array using minimum number of malloc() calls.
I want to access the array using subscripts, p[i][j].
#define ROW 3
#define COL 2
int main()
{
void **ptr = malloc( ROW*COL* sizeof(int) );
int (*p)[COL] = ptr;
int i, j;
for( i = 0; i < ROW; ++i )
for( j = 0; j < COL; ++j )
scanf("%d", &ptr[i][j]);
for( i = 0; i < ROW; ++i )
{
for( j = 0; j < COL; ++j )
printf("%d ", p[i][j]);
printf("\n");
}
return 0;
}
The program is outputting correctly whatever is the input.
But, it is showing Runtime error . Why?
If the array dimensions are known at compile-time (as in your example), then you can indeed allocate memory in one
malloccall. But you have to use the proper pointer type to access that memory. In your case that would be yourppointer. Youppointer is declared correctly, but you for some reason are completely ignoring its existence inscanfand usingptrinstead.Stop trying to use
ptrfor array access. Usep. Access your array elements asp[i][j]and it should work.In fact, I would get rid of
ptrentirely and do memory allocation in the following wayMoreover, since both dimensions are known at compile time, you can actually allocate it as
but in this case you’ll have to remember to access the array as
(*p)[i][j](note the*). Choose whichever method you prefer.