与此https://stackoverflow.com/a/21213612/1423473
相关的另一个问题我正在尝试连续为3d数组分配内存
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;
}
}
}
此代码在a[i][j][k] = 0
在执行时,我在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
它让我很神秘。我在这段代码中犯了什么样的错误?或者有一些替代解决方案?
答案 0 :(得分:1)
a[i] = (T**)(buff + (i * y * z));
您正在缓冲区内部存储一些指针。我怀疑这是故意的。试试这个:
a[i] = new T*[y];
这个很好,因为它应该指向缓冲区内部:
a[i][j] = (T*)(buff + i*y*z + j*z);