I'm writing an object called 'Matrix'. For parameters, the user specifies the number of rows and columns to be created. The constructor is being called in the Main class via:
Matrix* matrix = new Matrix(2, 3);
The constructor is prototyped in an *.h file and is implemented in a *.cpp file as follows (with the private variables included for the sake of clarification):
double** arr;
int rows;
int cols;
Matrix::Matrix(int numRows, int numCols) {
rows = numRows;
cols = numCols;
arr = new double*[numCols];
for (int i = 0; i < numRows; ++i) {
for (int x = 0; x < numCols; ++x) {
arr[i][x] = 0;
}
}
}
When the program executes (compiled in Visual Studio) it builds, executes, and throws an exception similar to:
Exception thrown at 0x00091BCC in Matrix Project.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
I can only assume this means I'm not looping through the array properly as it breaks on line arr[i][x] = 0
in the nested for
loop.
Would anyone be able give me some tips as to why this is breaking? How can I declare the array in a way that doesn't require one long loop being manipulated mathematically?
Thank you in advance!
[EDIT]
Anton provided that I need to allocate the memory to each row. When modifying the original nested loops to the following, the program executed successfully. Thank you!
for (int i = 0; i < numRows; ++i) {
arr[i] = new double[cols];
for (int x = 0; x < numCols; ++x) {
arr[i][x] = 0;
}
}