Why is new int[n] valid when int array[n] is not?

前端 未结 9 2221
暗喜
暗喜 2020-12-31 02:00

For the following code:

foo(int n){
    int array[n];
}

I understand that this is invalid syntax and that it is invalid because the c++ sta

9条回答
  •  灰色年华
    2020-12-31 02:38

    int array[n] allocates a fixed-length array on the call stack at compile-time, and thus n needs to be known at compile-time (unless a compiler-specific extension is used to allow the allocation at runtime, but the array is still on the stack).

    int *array = new int[n] allocates a dynamic-length array on the heap at run-time, so n does not need to be known at compile-time.

提交回复
热议问题