Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

memory

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?
like image 838
Mihran Hovsepyan Avatar asked Mar 20 '11 12:03

Mihran Hovsepyan


2 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. :)

like image 95
Prasoon Saurav Avatar answered Oct 19 '22 22:10

Prasoon Saurav


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.

like image 32
Jonathan Leffler Avatar answered Oct 20 '22 00:10

Jonathan Leffler