2016-12-01 35 views
-1

我想創建一個二維數組,其大小隻在運行時已知。試圖創建一個二維數組,其大小隻有在運行時已知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)); 
+2

I *高度開始*建議你閱讀一本好的C++書。通過試驗和錯誤學習C++或從網絡中隨機選擇的片段將結束不佳,相信我。 –

+0

你知道行數嗎? –

+0

@BaummitAugen,但它不是隨機片段,它是一個很好的stackoverflow答案... –

回答

0
#include <iostream> 
#include <string> 
#include <fstream> 


int main() 
{ 
    std::ifstream myFile; 
    myFile.open("input.txt", std::ios::in); 
    int num_cols; 
    myFile >> num_cols; 
    int num_rows = 10; 


    int** HArray = new int*[num_rows]; 
    for (int i = 0; i < num_rows; ++i) 
    { 
     HArray[i] = new int[num_cols]; 
    } 

    return 0; 
} 
-1

可用在C創建一個二維數組++從雙指針

int  ** matrix; 
matrix = new int * [num_cols]; 
for (int i = 0; i < num_cols; i++){ 
    matrix[i] = new int [num_rows]; 
} 
+0

「雙指針」具有誤導性,它是指向int的指針的指針,而不是指向double的指針。 – Robert

+0

另一個問題是,如果矩陣沒有參差不齊(不同的行大小),這是使用循環創建一個矩陣的最糟糕的方式(儘管這看起來是最顯示的方式)。爲了更有效地做到這一點,[看到這個答案](http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21​​944048#21944048) – PaulMcKenzie

相關問題