After reading tutorials, I adopted a way to create 2-D
array with malloc
. But to my surprise, changing allocation code with many variants, gives me the same output.
Consider:
#include<stdio.h>
#include<conio.h>
void main()
{
int **ptr;
int row=3,col=5,i,j;
*ptr=(int **) malloc(sizeof(int *));
for(i=0;i<3;i++)
{
ptr[i]=(int *) malloc(sizeof(int )*col);
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
ptr[i][j]=1;
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("val %d",ptr[i][j]);
free(ptr[i][j]);
}
printf("\n");
}
free(ptr);
getch();
}
(sorry for an old compiler-turboc 3 , its a compulsion)
when the statement :
*ptr=(int **) malloc(row*col*sizeof(int *));
is changed to
*ptr=(int **) malloc(sizeof(int *));
or to
*ptr=(int *) malloc(sizeof(int *));
or
*ptr=(int ) malloc(sizeof(int *));
or
*ptr=(int **) malloc(row*sizeof(int *));
....
GIVES me the same output, that is an array of 3*4
with all 1's.
Why is is so?