Dec 24, 2011 at 8:11pm UTC
Dears,
I am in need of writing a program of Dynamic Memory allocation to a 2-Dimensional array. I have written two programs, now I am in confusion which program is correct one. Kindly suggest me.
Here I am copying the code:
Program 1:
***********
#include <stdio.h>
#include <malloc.h>
int main()
{
int *a[5][5], i, j, count = 1;
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
a[i][j] = (int *) malloc (sizeof(int));
*a[i][j] = count++;
}
}
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
printf("a[%d][%d] = %d\n",i,j,*a[i][j]);
}
}
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
free(a[i][j]);
}
}
return 0;
}
Program 2:
************
#include <stdio.h>
#include <malloc.h>
int main()
{
int *p[5], i, j, count = 0;
for(i = 0; i < 5; i++)
{
p[i] = (int *) malloc ( 5 * sizeof(int));
}
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
p[i][j] = ++count;
}
}
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
printf("p[%d][%d] = %d\n", i, j, p[i][j]);
}
}
for(i = 0; i < 5; i++)
{
free(p[i]);
}
}
Kindly let me know which one is correct.
Thank you in advance.
Regards,
Sanjeeva K Kanakam.