I want to put both 1-dimensional array pointer and 2-dimensional array pointer in a union, so I can access data either way. In the following program I would like to see the value 9 is printed out by both ways.
#include <iostream>
class A {
public:
union {
int** array2D;
int* array1D;
};
A() {
array2D = new int*[1];
array2D[0] = new int[1];
}
};
int main() {
A a;
a.array2D[0][0] = 9;
cout << a.array2D[0][0] << endl;
cout << a.array1D[0] << endl;
cout << a.array2D << endl;
cout << a.array1D << endl;
}
The actual output:
9
146989080
0x8c2e008 //Pointer address of array2D
0x8c2e008 //Pointer address of array1D
The addresses are identical and by definition multidimensional arrays are stored in the same way as are one-dimensional arrays. I wonder why the two couts print out different results? What did I miss?
EDIT: Thanks to the answers below, I can see what I missed. The fix for accessing data from array1D is:
cout << *( (int*) a.array1D[0]) << endl;
array1Dis 'holding' the pointer to the first row ofarray2D, in case you weren't aware of that.newwas the same to declaring a fixed-size array, that's what misled me.