This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Declaring Arrays


Nuwan Kodagoda wrote:

> int size;
> cin >> size;
> int myarray[size];

>  this seems to work perfectly under g++.

It's a GNU GCC extension, called VLA (variable length array). It is part of
C99, and might make it to C++0x.

> If you can create dynamic arrays this way, why bother using dynamic
> arrays using pointers ?
>
> int size;
> cin >> size;
> int * pmyarray = new int[size];

It's very different. A VLA doesn't allocate memory from the heap space but only
on the stack. The array you created is an automatic variable and will be freed
as soon as its scope exits. A dynamic allocation with 'new' gets the memory
from the heap, and has its own lifetime (that is, you need to explicitally
destroy it with 'delete').

VLA is similar to what alloca() does on some systems: it lets you allocate some
memory from the stack very fast, within the current scope. It's probably much
faster than using 'new' but you have to pay attention to stack limits and
lifetime issues.

Giovanni Bajo



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]