1

I've been always using arrays whose size are asked in the input by the user like:

int main(){
    int n;
    cin>>n;
    int arr[n];
}

I never faced any problem with this method but now I've read a lot of articles saying that this syntax is not supported by C++ as C++ needs array size at compile time or arrays must be made dynamically using new keyword. Could anybody make this clear if the above code:

  1. Is supported by new compilers and not by the old compilers. If yes, then after which version this syntax is supported?
  2. Allocates the array dynamically in Heap or is this static memory allocation in stack?
8
  • 4
    using std::vector is a better way to approach arrays. Then you can do resize to make the vector (array) as big as you want, and the memory is managed for you. Commented Jul 23, 2020 at 13:07
  • 1
    @Tu.Ma. the question is: which compilers? Commented Jul 23, 2020 at 13:08
  • 4
    Why do you wonder? What is the actual problem you're trying to solve? Why can't you use std::vector which is the standard way of handling run-time sized "arrays"? Commented Jul 23, 2020 at 13:10
  • 1
    Microsoft's Visual C++ compiler does not and probably never will support variable-length arrays (unless the C++ standard will ever require it) Commented Jul 23, 2020 at 13:13
  • 2
    Well, there are the usual suspects, but isn't it time to start using standard (since decades) containers like std::vector? Commented Jul 23, 2020 at 13:22

3 Answers 3

4

I clicked through most of the compilers available at https://godbolt.org/ and it seems that only the Microsoft Visual Studio compiler rejects it. GCC and Clang on several platforms are fine with this code.

Note that it is only an additional support, both compiler can decide to stop accepting the code, as it is non standard.

The array will be on the stack for both compilers.

Sign up to request clarification or add additional context in comments.

Comments

0

Modern C++ compilers usually don't support arrays with unknown size at compile-time. C style arrays like that allocate memory on the stack, using the "new" keyword" or malloc like in C will allocate them on the heap, though you will need to take care of their deletion then. What you might want to use is std::vector, which is on the "vector" header, it will dynamically allocate memory on the heap, allow for resizing at runtime and take care of it's own deletion when it goes out of scope.

Comments

0

Using std::vector, which any compiler should support

#include <vector>

int main(){
    int n;
    cin>>n;
    std::vector<int> arr(n);

    cout << "the size of my array is:" << arr.size();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.