11
void method(string a) {
  int n = a.size();
  int array[n];
}

The above code can compile correctly using gcc. How can the size of the array come from a non-constant variable? Does the compiler automatically translate the int array[n] to int* array = new int[n]?

user2621037
  • 326
  • 1
  • 3
  • 13

3 Answers3

6

How can the size of the array come from a non-constant variable?

Currently, because that compiler has a non-standard extension which allows you to use C's variable length arrays in C++ programs.

Does the compiler automatically translate the int array[n] to int* array = new int[n]?

That's an implementation detail. I believe GCC places it on the stack, like normal automatic variables. It may or may not use dynamic allocation if the size is too large for the stack; I don't know myself.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

dynamic allocation. The new keyword will do this with a pointer and some allocation.

int * ptr;
int n = a.size();
ptr = new int[n];
Jacob Minshall
  • 1,044
  • 9
  • 15
  • another benefit of this is that the pointer address can be returned from a function, where a statically created array is wiped off the stack when the function returns – Jacob Minshall Oct 20 '13 at 03:35
  • That variable ptr can be used just like an array, e.g. you can use the [] subscript like `ptr[a-1]` to access the last element of the array – Jacob Minshall Oct 20 '13 at 03:36
  • 4
    I'd argue that a *disadvantage* of this is that you need to explicitly manage the memory yourself and remember to call `delete[]` later. Really, just use a `std::vector`. – jamesdlin Oct 20 '13 at 03:37
  • 1
    I suggest using the edit button below your answer. However, using `new` is not commonly desired in C++. – chris Oct 20 '13 at 03:38
  • why so @chris ? And what is used instead? – Jacob Minshall Oct 20 '13 at 03:48
  • 2
    @JacobMinshall, Because managing your own memory adds unneeded complexity to your application. You might say it's simple to free your memory every time you use it, but if it's in a class, you need extra member functions, and throw in some exceptions and you've got lots of extra code. Instead, use the proper RAII container, such as a `std::vector` or a smart pointer. – chris Oct 20 '13 at 03:59
1

According to this the compiler allows this expression in C++ as far as C90/99.