Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size at run time without dynamic allocation is allowed?

I've been using C++ for a few years, and today I saw some code, but how can this be perfectly legal?

int main(int argc, char **argv) {     size_t size;     cin >> size;     int array[size];     for(size_t i = 0; i < size; i++)     {         array[i] = i;         cout << i << endl;     }      return 0; } 

Compiled under GCC.

How can the size be determined at run-time without new or malloc?

Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error.

Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5:

Only constants can be used to declare the size of automatic and static arrays.

Enlight me.

like image 371
syaz Avatar asked Apr 10 '09 10:04

syaz


People also ask

Can we give size of array at run time?

Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

Does array use dynamic memory allocation?

dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.

Can a dynamically allocated array change size?

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.


2 Answers

This is valid in C99.

C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.

Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like _alloca.

like image 60
mmx Avatar answered Oct 17 '22 04:10

mmx


This is known as VLAs (variable length arrays). It is standard in c99, but gcc allows it in c++ code as an extension. If you want it to reject the code, try experimenting with -std=standard, -ansi and -pedantic options.

like image 25
jpalecek Avatar answered Oct 17 '22 04:10

jpalecek