[英]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數組。
但是請記住在使用后將其delete
或free
。
您可以使用std::vector<Type>(n*m)
,這可能是最好的方法。
但是,如果您想繼續使用該數組,我想如果您通過調用new / malloc在堆上而不是堆棧上分配內存,它將可以編譯。 但是請提醒自己,釋放內存之后,請在操作之前檢查用戶輸入,以防止惡意輸入。
數組需要常量paras。
可以使用vector< vector <int> >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.