Please go through the code below,
I want to create a dynamic 2 dimensional int array, to be created at run time.
Code:
#include <stdio.h>
#include <stdlib.h>
void point(int **a,int row,int col)
{
int i;
//printf ("\n%u\n",a);
a=(int **) malloc(sizeof(int *) * row);
if(a==NULL)
{
printf ("CAnnot allot space");
exit(1);
}
for(i=0;i<col;++i)
{
a[i]=(int *) malloc(sizeof(int) * col);
if(a[i]==NULL)
{
printf ("CAnnot allot space");
exit(1);
}
}
}
void main()
{
int **p;
int i,j;
int row=7,col=7;
randomize();
//printf ("\n%u\n",p);
point(p,row,col);
for(i=0;i<row;++i)
{
for(j=0;j<col;++j)
{
p[i][j]=random(10);
//if(i==6 || i==9)
printf ("%d\n",p[i][j]);
}
}
printf ("Alloted\n");
for(i=0;i<row;++i)
{
for(j=0;j<col;++j)
{
//if(i==6 || i==9)
printf ("p[%d][%d] = %d\n",i,j,p[i][j]);
}
}
}
But it gives the following result :
2
3
6
4
0
5
8
3
7
5
2
3
1
4
8
2
4
0
6
0
7
1
1
6
7
9
3
6
1
8
2
9
5
4
6
0
1
6
5
6
8
2
1
7
1
2
3
6
1
Alloted
p[0][0] = 2
p[0][1] = 3
p[0][2] = 6
p[0][3] = 4
p[0][4] = 0
p[0][5] = 5
p[0][6] = 8
p[1][0] = 3
p[1][1] = 7
p[1][2] = 5
p[1][3] = 2
p[1][4] = 3
p[1][5] = 1
p[1][6] = 4
p[2][0] = 8
p[2][1] = 2
p[2][2] = 4
p[2][3] = 0
p[2][4] = 6
p[2][5] = 0
p[2][6] = 7
p[3][0] = 0
p[3][1] = 1
p[3][2] = 6
p[3][3] = 5
p[3][4] = 6
p[3][5] = 8
p[3][6] = 2
p[4][0] = 0
p[4][1] = 1
p[4][2] = 6
p[4][3] = 5
p[4][4] = 6
p[4][5] = 8
p[4][6] = 2
p[5][0] = 0
p[5][1] = 1
p[5][2] = 6
p[5][3] = 5
p[5][4] = 6
p[5][5] = 8
p[5][6] = 2
p[6][0] = 18431
p[6][1] = 14355
p[6][2] = 2048
p[6][3] = 18178
p[6][4] = 9471
p[6][5] = -9729
p[6][6] = 14357
There are two bold parts in above output
1st shows the acutal value stored, which is later displayed (as shwon in 2nd bold part), why does this happen.
Though the same code works for smaller number well.
Manish B