It is always frustrating when I try to declare an array in C++. Maybe I just do not understand how array works. The following situation is I am writing a constructor which initializes the row, col, and multi-dimensional array. The code runs into an error.
I already declared both row, col, and array variables in the private class members. When I run the main, the row and col will pass into constructor. The array should be initialized successfully?
#include <bits/stdc++.h>
using namespace std;
class SpreadSheet {
private:
int r, c;
string table[r][c];
public:
SpreadSheet(int row, int col) {
r = row; c = col;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
table[i][j] = ' ';
}
}
}
};
int main() {
SpreadSheet t(3, 3);
return 0;
}
Below is the error log I got. I guess I understand the basic logic behind it. The array size has to be assigned before compiling the code. So what is the correct way around this problem?
demo.cc:7:16: error: invalid use of non-static data member ‘SpreadSheet::r’
7 | string table[r][c];
| ^
demo.cc:6:7: note: declared here
6 | int r, c;
| ^
demo.cc:7:19: error: invalid use of non-static data member ‘SpreadSheet::c’
7 | string table[r][c];
| ^
demo.cc:6:10: note: declared here
6 | int r, c;
| ^
demo.cc: In constructor ‘SpreadSheet::SpreadSheet(int, int)’:
demo.cc:15:9: error: ‘table’ was not declared in this scope
15 | table[i][j] = ' ';
|