Deselect a 3D array
I am working in C ++ and I need to allocate a 3d array from two pairs. This is the code used to highlight:
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");
}
}
}
Distribution has no problem. Finally, when I need to undo the "cube", there are some problems. This is the code:
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
free(cellMatrix[i][j]);
}
free(cellMatrix[i]);
}
free(cellMatrix);
The program stops while freeing cellMatrix [i], printing this error message (Visual Studio Pro '13)
HOG.exe triggered a breakpoint.
Can anyone help me with this problem?
+3
source to share
1 answer
From your error message, I suspect you are in debug mode and (accidentally) set a breakpoint on the line free(cellMatrix[i]));
.
Following Wyzard's suggestion, you can allocate a contiguous array with
double cellArray[] = new double[N*M*B];
and index it with
double& cell(int i, int j, int k) { return cellArray[i + j*N + k*N*M]; }
+1
source to share