Another question related to this https://stackoverflow.com/a/21213612/1423473
I'm trying to allocate memory for 3d array contiguously
T* buff = new T [x * y * z];
for(int i = 0; i < x * y * z; i++) {
buff[i] = 2; // 2 for debug purposes
}
T*** a = new T **[x];
for(int i=0; i<x; ++i)
{
a[i] = (T**)(buff + (i * y * z));
for(int j=0; j<y; ++j)
{
a[i][j] = (T*)(buff + i*y*z + j*z);
for(int k=0; k<z; ++k)
{
a[i][j][k] = 0;
}
}
}
This code leads to SIGSEGV at the line a[i][j][k] = 0
At the execution time I have this result in gdb
(gdb) n
343 a[i][j] = (T*)(buff + i*y*z + j*z);
(gdb) x/20d buff
0xbb7350: 2 2 2 2
0xbb7360: 2 2 2 2
0xbb7370: 2 2 2 2
0xbb7380: 2 2 2 2
0xbb7390: 2 2 2 2
(gdb) x/20d a
0x87ac80: 12284752 0 8955856 0
0x87ac90: -134410640 32767 -288938360 32767
0x87aca0: -134496320 32767 -288949632 32767
0x87acb0: -288949584 32767 -288949536 32767
0x87acc0: -134300384 32767 -134795808 32767
(gdb) n
345 for(int k=0; k<z; ++k)
(gdb) x/20d buff
0xbb7350: 12284752 0 2 2
0xbb7360: 2 2 2 2
0xbb7370: 2 2 2 2
0xbb7380: 2 2 2 2
0xbb7390: 2 2 2 2
(gdb) print (int)buff
$6 = 12284752
It looks for me very mysterious. What kind of mistakes I have in this code? Or there are some alternative solutions?