2D Dynamic array - help

The below memory allocation for a and a1 are correct?.
I am getting incorrect values while printing array contents
I ran it in Linux with g++ compiler


Pg1 and Pg2 are same exceptin pg2 - array dimensions are stored in variable

Pg1
int (*a)[2];
a = (int (*)[2])malloc(3 * sizeof(int));
a[0][0]=3;
a[0][1]=4;
a[0][2]=5;
a[1][0]=6;
a[1][1]=7;
a[1][2]=8;


Pg2

int n=2;
int m=3;
int (*a1)[n];
a1 = (int (*)[n]) malloc (m*sizeof(int));
a1[0][0]=3;
a1[0][1]=4;
a1[0][2]=5;
a1[1][0]=6;
a1[1][1]=7;
a1[1][2]=8;

cout<<"\n"<<a1[0][0]<<a1[0][1]<<a1[0][2]<<a1[1][0]<<a1[1][1]<<a1[1][2];
cout<<"\n"<<a[0][0]<<a[0][1]<<a[0][2]<<a[1][0]<<a[1][1]<<a[1][2];


Output

346678
8811-111075563152
Topic archived. No new replies allowed.