I'm trying to create a 2D array in c++ whose size is only known at runtime.
I tried doing the following:
std::ifstream myFile;
myFile.open("input.txt",std::ios::in);
int num_cols;
myFile >> num_cols;
int num_rows = 10;
int *HArray;
HArray = (int*) malloc(sizeof(int)*num_cols*num_rows);
But when I try this:
for (int i = 0; i < num_rows; i++) {
for(int j = 0; j < num_cols; j++) {
HArray[i][j] = i*j + 34*j;
}
}
I get the following error during compilation:
Error 2 error C2109: subscript requires array or pointer type
How do I allocate the memory for HArray such that I can use the indices [i][j] to access and assign values to the array?
I tried following @Uri's answer available here, but the program immediately crashes, and I didn't really understand what was going on either.
EDIT:
I decided to use the following
std::vector<std::vector<int>> HArray(num_rows, std::vector<int>(num_cols));