簡體   English   中英

雙數組,大小作為用戶輸入

[英]Double array with size as user input

我想做這樣的事情

int n,m; //or cin>>n>>m;

a[n][m];

//then do whatever with the array

問題是Visual Studio給我錯誤,而dev c ++沒有。 我想在VS中編譯它。

即使你的編譯器支持VLA(變長數組),你沒有宣布a正確:

int a[n][m];
^^^

您應該使用std::vector這是一種標准方式

std::vector<std::vector<int> > a(n, std::vector<int>(m));

這取決於編譯器...
對於此類需求,始終建議使用std::vector
但是,如果必須這樣做 ,則可以像這樣在堆上分配該內存...

使用new (在C ++中推薦)...

cout << "Enter n & m:";
int n, m;
cin >> n >> m;

int** p = new int*[n];
for (int i = 0 ; i < n; i++) {
    p[i] = new int[m];
}

或使用malloc (在C中執行。不建議在C ++中使用)...

cin >> n >> m;

int** p = (int**) malloc (n * (int*));

for (int i = 0; i < n; i++) {
    p[i] = (int*) malloc(m * (int));
}

用於int的2D數組。

但是請記住在使用后將其deletefree

您可以使用std::vector<Type>(n*m) ,這可能是最好的方法。

但是,如果您想繼續使用該數組,我想如果您通過調用new / malloc在堆上而不是堆棧上分配內存,它將可以編譯。 但是請提醒自己,釋放內存之后,請在操作之前檢查用戶輸入,以防止惡意輸入。

數組需要常量paras。

可以使用vector< vector <int> >

在即將到來的C ++ 14標准中提出了可變長度數組 ,但尚未在該語言中提出。

但是,您可以使用任意類型的std::vectorstd::vector

喜歡

std::vector<std::vector<int>> a(n, std::vector<int>(m));

上面的聲明創建了一個由整數向量,大小為n的外部向量和大小為m的內部向量組成的向量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM