简体   繁体   中英

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

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.

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

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

根据这个编译器允许在C ++中,只要C90 / 99此表达式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM