简体   繁体   中英

Double array with size as user input

I want to do something like this

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

a[n][m];

//then do whatever with the array

The problem is that Visual Studio gives me errors, while dev c++ doesn't. I want to compile it in VS.

Even if your compiler supports VLA(Variable Length Arrays), you didn't declared a properly:

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

You should use std::vector which is a standard way

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

That depends on the compiler...
Use of std::vector is always recommended for such need.
But if you have to , then you can allocate that memory on the heap like this...

using new (recommended in 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];
}

or using malloc (Do it in C. Not recommended in C++)...

cin >> n >> m;

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

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

for a 2D array of int s.

But remember to delete or free it after your use.

You could use a std::vector<Type>(n*m) , that would probably be the nicest way.

If however you want to stay with the array, I guess that it would compile if you allocate the memory on the Heap instead of the stack by calling new/malloc. But remind yourself of freeing the memory afterwards and please check the user input before you do it to prevent malicious inputs.

array needs constant paras.

instaead, you can use vector< vector <int> >

Variable length arrays are proposed in the upcoming C++14 standard , but not yet in the language.

You can however use a std::vector of std::vector of whatever type you want.

Like

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

The above declaration create a vector of vectors of integers, the outer vector of size n and the inner vector of size m .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM