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

后端 未结 3 1881
名媛妹妹
名媛妹妹 2020-12-02 00:52
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 fr

相关标签:
3条回答
  • 2020-12-02 01:12

    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.

    0 讨论(0)
  • 2020-12-02 01:17

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

    int * ptr;
    int n = a.size();
    ptr = new int[n];
    
    0 讨论(0)
  • 2020-12-02 01:20

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

    0 讨论(0)
提交回复
热议问题