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

前端 未结 9 2169
暗喜
暗喜 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:36

    You can allocate memory statically on the stack or dynamically on the heap.

    In your first case, your function contains a declaration of an array with a possible variable length, but this is not possible, since raw arrays must have fixed size at compile time, because they are allocated on the stack. For this reason their size must be specified as a constant, for example 5. You could have something like this:

    foo(){
        int array[5]; // raw array with fixed size 5
    }
    

    Using pointers you can specify a variable size for the memory that will be pointed, since this memory will be allocated dynamically on the heap. In your second case, you are using the parameter n to specify the space of memory that will be allocated.

    Concluding, we can say that pointers are not arrays: the memory allocated using a pointer is allocated on the heap, whereas the memory allocated for a raw array is allocated on the stack.

    There are good alternatives to raw arrays, for example the standard container vector, which is basically a container with variable length size.

    Make sure you understand well the difference between dynamic and static memory allocation, the difference between memory allocated on the stack and memory allocated on the heap.

提交回复
热议问题