I started learning C++ and I wanted to implement a simple 2D array and get its size without using std::vector
. However I run into weird errors with my second dimension:
int **data= new int*[2];
for (int i = 0; i<2;i++){
data[i] = new int[3];
}
data[0][0] = 1;
data[0][1] = 2;
data[0][2] = 3;
data[1][0] = 4;
data[1][1] = 5;
data[1][2] = 6;
data[1][25] = 20; //Should segfault? AAAAA
cout << "Data[1][25] = " << data[1][25] << endl; //Should segfault, no?
int n = sizeof(data[0]) / sizeof(int);
int m = sizeof(data) / sizeof(int);
cout << "M is " << m << " N is " << n << endl;// Reports m = 2, n =2?!?!? BBBB
At AAAA
I should be getting segfault, no? Instead I am able to assign a value and later read it. The value of data[1][any]
is zero, like it has been initialized. This is only a problem in the second dimension, the first dimension behaves as expected.
Later at BBBB
I am not getting an accurate size for n
. Am I doing something wrong?