我在 C++ 中工作,我必须分配一个 3d double 组。这是用于分配的代码:
cellMatrix = (double***)malloc(N*sizeof(double**));
if (cellMatrix == NULL)
{
errorlog("Allocation Error -> CellMatric can't be created");
}
for (int k = 0; k < N; k++)
{
cellMatrix[k] = (double**)malloc(M*sizeof(double*));
if (cellMatrix[k] == NULL)
{
errorlog("Allocation Error -> *CellMatric can't be created");
}
for (int i = 0; i < M; i++)
{
cellMatrix[k][i] = (double*)malloc(B*sizeof(double));
if (cellMatrix[k][i] == NULL)
{
errorlog("Allocation Error -> **CellMatric can't be created");
}
}
}
分配没有任何问题。最后,当我不得不取消分配“多维数据集”时,出现了一些问题。这是代码:
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
free(cellMatrix[i][j]);
}
free(cellMatrix[i]);
}
free(cellMatrix);
程序在 cellMatrix[i] 的释放期间停止,打印此错误消息 (Visual Studio Pro '13)
HOG.exe has triggered a breakpoint.
有人可以帮我解决这个问题吗?
最佳答案
根据您的错误消息,我怀疑您正在 Debug模式下运行并且(无意中)在 free(cellMatrix[i]));
行设置了一个断点。
按照 Wyzard 的建议,您可以分配一个连续的数组
double cellArray[] = new double[N*M*B];
并索引到它
double& cell(int i, int j, int k) { return cellArray[i + j*N + k*N*M]; }
关于c++ - 取消分配 3D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193176/