Reputation: 4633
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.
Upvotes: 0
Views: 120
Reputation: 1902
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.
Upvotes: 1
Reputation: 409176
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
.
Upvotes: 0
Reputation: 207
array needs constant paras.
instaead, you can use vector< vector <int> >
Upvotes: 0
Reputation: 56479
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));
Upvotes: 2
Reputation: 5102
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.
Upvotes: 0