How to declare a (multi-dimensional) array with value inputted by the user?
arrays, c++, multidimensional-array
Solution
This is not standard C++ but many compiler including gcc and clang support variable length arrays as an extension in C++ even though it is a C99 feature. Althought both `gcc` and `clang` will warn you this is an extension if the `-pedantic` flag is used with a message similar to this:
warning: ISO C++ forbids variable length array ‘array’ [-Wvla]
An alternative in standard C++ would be to use std::vector or dynamic allocation via new:
int x;
cin >> x;
int *array new int[x] ;
//...
delete [] array ;
the 2D dynamic allocation case is well covered in How do I declare a 2d array in C++ using new?. Using a container is probably better since you do not have to worry about deleting the allocated memory afterwards.
Problem
What we're being taught at school is this: ``` int x; cin >> x; int array[x]; ``` OR ``` int x, y; cin >> x >> y; int array[x][y]; ``` However, I am aware that it's invalid code in C++. But even if it is, it still does the job and works as expected, however, I'm looking to find the answer of how it's properly done?