Answer the question
In order to leave comments, you need to log in
How to return a value from a 2D array in the ReturnValue method?
class Matrix {
private:
int rows;
int cols;
int** arr = new int* [rows];
public:
Matrix(int _rows, int _cols) {
rows = _rows;
cols = _cols;
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = 0;
}
}
//// filling rand values
int chance = rand() % 50;
double amountNotNull = floor(((rows * cols) / 100.0) * chance);
for (int i = 0; i < amountNotNull; i++) {
int rowsX;
int colsY;
rowsX = rand() % cols;
colsY = rand() % rows;
if (arr[rowsX][colsY] != 0) {
rowsX = rand() % cols;
colsY = rand() % rows;
}
else {
arr[rowsX][colsY] = (rand() % 100) + 1;
}
}
}
int ReturnValue(int rows, int cols) {
return *&arr[rows][Matrix::cols];
}
void print() {
cout << "Matrix: " << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
};
int main()
{
Matrix a(5, 5);
a.print();
int b = a.ReturnValue(0, 0);
cout << b;
}
Answer the question
In order to leave comments, you need to log in
1. The syntax for getting an element by index is incorrect, in fact, the combination "*&" before the pointer does nothing, it is better to remove it.
2. Variables in the ReturnValue method are not speaking, it is desirable to rename them to row, col (without multiple endings). Because you are trying to get a single value by row and column , not by row and column .
3. The method uses Matrix::cols, this is also incorrect, in your case you just need to use cols. If you needed to use exactly the variable set inside the class, and not the one that came in the method parameters, then it would be correct to write this->cols.
Summarizing the above, the correct code might look like this:
int ReturnValue(int row, int col) {
return arr[row][col];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question