I have created a two dimensional array on the heap. And I want to fill the array with numbers. I have tried two ways of doing this. The first attempt sort of works, but the problem is that the program will crash when I try to delete it. The second attempt that I did made it possible to delete the array after I have used it, but the array is not filled the correct way.
So here is how I declared the two dimensional array:
int** matrix = new int*[rowSize];
for (int i = 0; i < rowSize; i++) {
matrix[i] = new int[ColSize];
}
And then I fill it like this:
int matrixI0[]{1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1};
int matrixI1[]{1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1};
int matrixI2[]{1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1};
int matrixI3[]{1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI4[]{1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI5[]{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI6[]{0, 0, 1, 0, 0, 0, 1, 1, 1, 0 ,0, 1};
matrix[0] = matrixI0;
matrix[1] = matrixI1;
matrix[2] = matrixI2;
matrix[3] = matrixI3;
matrix[4] = matrixI4;
matrix[5] = matrixI5;
matrix[6] = matrixI6;
When I am filling it this way the array is behaving the way I want and I am getting the expected result in a later method that uses this array.
However when I try to delete it:
for (int i = 0; i < rowSize; ++i) {
delete[] matrix[i];
}
delete[] matrix;
I get an thrown exception with the following error message "Test.exe has triggered a breakpoint." And of course if I run it in release the program will crash.
My second attempt of filling the array looked like this:
int matrixI0[]{1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1};
int matrixI1[]{1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1};
int matrixI2[]{1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1};
int matrixI3[]{1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI4[]{1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI5[]{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1};
int matrixI6[]{0, 0, 1, 0, 0, 0, 1, 1, 1, 0 ,0, 1};
matrix[0][0] = *matrixI0;
matrix[1][0] = *matrixI1;
matrix[2][0] = *matrixI2;
matrix[3][0] = *matrixI3;
matrix[4][0] = *matrixI4;
matrix[5][0] = *matrixI5;
matrix[6][0] = *matrixI6;
And now there is no problem when I am deleting the array, but now the array is not behaving the way I want it to, and when I test the method that uses the array I get the same result as if the array would just have been filled with zeros.
I know that I am not doing it right in the second attempt but I just did this to see what had to be done so the array could be succesfully deleted.
So to sum this up my question is how should I fill the two dimensional array in a way that it is correctly filled, but it will also succesfully be deleted?
Thanks!