I wrote this simple function to learn about arrays in C++ (I am using CERN's ROOT as a C++ compiler):
int** vec() {
int n = 2;
int m = 3;
int *pointer[m];
for (int i=0; i<m; i++) {
pointer[i] = new int[n];
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
pointer[i][j] = -1;
}
}
return pointer;
}
After compiling the code, which I have saved as test.C, I create two pointers to two-arrays in what seems to me an identical manner, but with different results. The first was works exactly as I expected both methods to work:
root [0] .L test.C+
root [1]
root [1] int** mat1;
root [2] int** mat2;
root [3] mat1 = vec();
root [4] mat2 = vec();
root [5] mat1[0][0]
(int)(-1)
root [6] mat2[0][0]
(int)(-1)
Okay, nothing surprising there. But if I do all the stuff with mat1 before getting to mat2, I get the following very different result:
root [0] .L test.C+
root [1]
root [1] int** mat1;
root [2] mat1 = vec();
root [3] mat1[0][0]
(int)(-460363344)
root [4]
root [4] int** mat2;
root [5] mat2 = vec();
root [6] mat2[0][0]
(int)(-1)
In this case, it appears that my function has not worked as far as mat1 is concerned. Can anyone help me understand what is going on here?