I'm new to C++ and the way 2D arrays work is confusing me. I've been reading online and trying to understand what's causing my specific issue, but have come up with nothing.
According to this Stack Overflow answer, I should be able to get a value in my 2D array by doing this: (*myArrayObject)[row][col]
, but it throws the following error:
error: invalid types 'int[unsigned int]' for array subscript
return (*myArrayObject)[row][col];
^
And if I try to do myArrayObject[row][col]
it throws the following error:
error: invalid initialization of non-const reference of types 'double&' from an rvalue of type 'double'
return myArrayObject[row][col];
^
Here's the full (related/concise) code in question:
main.cpp
#include "matrix.h"
using namespace std;
typedef unsigned int uint;
int main() {
Matrix * matrix; //This could be the problem, but not sure what else to do
matrix = new Matrix(10, 1);
for(uint i = 0; i < matrix->numRows(); ++i) {
for(uint j = 0; j < matrix->numCols(); ++j) {
cout << matrix->at(i,j) << " " << endl;
}
}
return 0;
}
matrix.h
typedef unsigned int uint;
class Matrix {
public:
Matrix(uint rows, uint cols); //Constructor
const uint numRows() const;
const uint numCols() const;
void setRows(const uint &);
void setCols(const uint &);
double & at(uint row, uint col);
private:
uint rows, cols;
int ** matrix; //This could also be the problem, but not sure what else to do
void makeArray() {
matrix = new int * [rows];
for(uint i = 0; i < rows; ++i) {
matrix[i] = new int [cols];
}
}
};
matrix.cpp
#include "matrix.h"
typedef unsigned int uint;
Matrix::Matrix(uint rows, uint cols) {
//Make matrix of desired size
this->setRows(rows);
this->setCols(cols);
//Initialize all elements to 0
for(uint i = 0; i < rows; ++i) {
for(uint j = 0; j < cols; ++j) {
this->matrix[i][j] = 0;
}
}
}
const uint Matrix::numRows() const {
return this->rows;
}
const uint Matrix::numCols() const {
return this->cols;
}
void Matrix::setRows(const uint & rows) {
this->rows = rows;
}
void Matrix::setCols(const uint & cols) {
this->cols = cols;
}
double & Matrix::at(uint row, uint col) {
return matrix[row][col]; //NOT WORKING
}
SOLUTION:
Changes made to matrix.h:
double ** matrix;
void makeArray() {
matrix = new double * [rows];
for(uint i = 0; i < rows; ++i) {
matrix[i] = new double [cols];
}
}
Changes made to matrix.cpp:
added makeArray()
to constructor.