我想創建一個二維數組,其大小隻在運行時已知。試圖創建一個二維數組,其大小隻有在運行時已知c +
我試着做以下幾點:
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);
但當我嘗試這個辦法:
for (int i = 0; i < num_rows; i++) {
for(int j = 0; j < num_cols; j++) {
HArray[i][j] = i*j + 34*j;
}
}
我在編譯過程中出現以下錯誤:
錯誤2錯誤C2109:下標需要數組或指針類型
如何分配的內存HArray使得我可以使用指數爲[i] [j]來訪問和將值分配給該數組?
我試過了@Uri的答案可用here,但是程序立即崩潰了,我也不是很瞭解發生了什麼事情。
編輯:
我決定使用以下
std::vector<std::vector<int>> HArray(num_rows, std::vector<int>(num_cols));
I *高度開始*建議你閱讀一本好的C++書。通過試驗和錯誤學習C++或從網絡中隨機選擇的片段將結束不佳,相信我。 –
你知道行數嗎? –
@BaummitAugen,但它不是隨機片段,它是一個很好的stackoverflow答案... –