Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ declare an array based on a non-constant variable?

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

like image 374
user2621037 Avatar asked Oct 20 '13 03:10

user2621037


1 Answers

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.

like image 124
Mike Seymour Avatar answered Sep 20 '22 17:09

Mike Seymour