Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Why can't I create an array of size n? [duplicate]

Writer Matthew Martinez

Possible Duplicate:
Why can't I create an array with size determined by a global variable?

This is definition of simple array with constant size 4, which is stored in stack memory:

int array[4];

Now If I want to declare array of dynamic size in stack it seems that I should write this code:

int n;
cin >> n;
int array[n];

But as we know this is not allowed in C++ and instead we can write this one, which will create the array in dynamic memory (i.e. heap):

int n;
cin >> n;
int *array = new int[n];

But this is more slower and (because of using new operator) and requires to call delete [] operator after we finish our work with array.

So my question is here:

  • Why is it that C++ don't allow you to create array of dynamic length in stack memory?
0

5 Answers

int n;
cin >> n;
int array[n];

This will work if use g++. g++ support VLAs as an extension. However ISO C++ mandates size of an array to be a constant expression i.e the size must be known at compile time.

Why is it that C++ don't allow you to create array of dynamic length in stack memory?

Simple answer "Because the standard says so". Even the upcoming C++ Standard (C++0x) is not going to allow Variable Length Arrays.

BTW we always have std::vector in C++. So there's no reason to worry. :)

2

C99 does allow variable length arrays (VLAs); C89 did not.

void function(int n)
{ int array[n]; ...
}

C++ (98, 03) does not allow VLAs in the same way that C99 does, but it has vectors and related types which are better in many respects.

2

There is no language called C/C++. There is C, which allows variable-length arrays (VLAs) since 1999, and there is C++, which doesn't allow.

To answer your question "why" - C++ standard body for whatever reason didn't include VLAs into C++ standard.

int n;
cin >> n;
int array[n];

In C++, the size of the array must be known at compile time. But in your code the size will be known at runtime. That is not allowed by the language!

1

In addition to other answers:
My speculation is that the C++ standard board thinks that the C-style arrays are obsolete and evil, and promotes using of std::vector (which has this feature by design) this way.