问题
How can I create a 3D-array only with Qt-Objects? The array should be a 3D-integer-array. I have tried to create a standard 3D-array on the heap. To allocate the memory on the heap works fine. I got an error if i want to deallocate the memory.
const int scalefaktor = 16;
int*** anzPixel3d = new int**[256/scalefaktor];
for (int i = 0; i <= 256/scalefaktor ; i++)
{
anzPixel3d[i] = new int*[256/scalefaktor];
for (int k = 0; k <= 256/scalefaktor ; k++)
{
anzPixel3d[i][k] = new int[256/scalefaktor];
}
}
for (int j = 0; j <= 256/scalefaktor ; j++)
{
for (int m = 0; m <= 256/scalefaktor ; m++)
{
delete [] anzPixel3d[j][m];
}
delete [] anzPixel3d[j];
}
delete [] anzPixel3d;
For this project I use Qt4.8 and the Qt-Creator 2.7.0. I use the MSVC2010 compiler.
The error-message is: HEAP CORRUPTION DETECTED: after Normal block (#31715) at 0x006E3C0. CRT detected that the application wrote to memory after end of heap buffer.
回答1:
#include <QCoreApplication>
#include <QVector>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int dim_0 = 3;
int dim_1 = 3;
int dim_2 = 3;
int default_val = 0;
QVector < QVector < QVector< int > > > vec(dim_0,
QVector < QVector <int > > (dim_1,
QVector < int > (dim_2, default_val)));
for( int i = 0; i < dim_0; i++)
{
for ( int j = 0; j < dim_1; j++)
{
for ( int k = 0; k < dim_2; k++)
{
vec[i][j][k] = i*100 + j*10 + k;
}
}
}
qDebug() << vec;
return a.exec();
}
Hope that helps.
回答2:
HEAP CORRUPTION occurred because of <=
. If you replace <=
to <
, your code will work.
const int scalefaktor = 16;
int*** anzPixel3d = new int**[scalefaktor];
for (int i = 0; i < scalefaktor ; i++)
{
anzPixel3d[i] = new int*[scalefaktor];
for (int k = 0; k < scalefaktor ; k++)
{
anzPixel3d[i][k] = new int[scalefaktor];
}
}
for (int j = 0; j < scalefaktor ; j++)
{
for (int m = 0; m < scalefaktor ; m++)
{
delete [] anzPixel3d[j][m];
}
delete [] anzPixel3d[j];
}
delete [] anzPixel3d;
来源:https://stackoverflow.com/questions/16971704/qt-3d-array-with-qt-objekts-like-qvector