Creation of 2-Dimentional array with dynamic memory allocation

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.
Hi when i run this code i get the garbage value .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 #include "stdafx.h"
#include <iostream> 
using namespace std ; 


int _tmain(int argc, _TCHAR* argv[])
{
	int *p[5] , count = 0 ; 
	for( int i = 0 ; i < 5; i++ ) 
		for( int j = 0 ; j < 5; j++ ) 
		{
				p[j] = new int[1]; 
				p[i][j] = count++;
		}


	for( int i = 0 ; i < 5; i++ ) 
		for( int j = 0 ; j < 5; j++ ) 
		{
				cout<<"\n p["<<i<<"]["<<j<<"] = "<<p[i][j] ;
		}


	for(int i = 0; i < 5; i++ )
		delete p[i];

	return 0;
}


I am not able to understand why ?
can some one please explain .
Thanks in advance .
Topic archived. No new replies allowed.