12
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]?

5
  • 5
    It's a compiler extension. Commented Oct 20, 2013 at 3:33
  • 3
    Use const. Use reference. Use vector Commented Oct 20, 2013 at 3:35
  • 2
    With GCC, compile your code with -pedantic-errors, and then see what it says! Commented Oct 20, 2013 at 3:39
  • @Nawaz: Then compile with -std=c++1y and see what it says. Commented Oct 20, 2013 at 3:41
  • @MikeSeymour: Hehe.... Commented Oct 20, 2013 at 3:59

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

int * ptr;
int n = a.size();
ptr = new int[n];

6 Comments

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
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
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.
I suggest using the edit button below your answer. However, using new is not commonly desired in C++.
@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.
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.