Whats the difference? Pointer to an array vs regular array

后端 未结 9 1738
梦如初夏
梦如初夏 2021-01-04 21:40

I\'m familiar with Java and trying to teach myself C/C++. I\'m stealing some curriculum from a class that is hosting their materials here. I unfortunately can\'t ask the tea

9条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 22:08

    On the one hand:

    int ar[10];
    

    is using memory allocated on the stack. You can think of it also locally available and while it is possible to pass a pointer / reference to otehr functions, the memory will be freed as soon as it goes out of scope (in your example at the end of the main method but that's usually not the case).

    On the other hand:

    int ar* = new int[10];
    

    allocates the memory for the array on the heap. It is available until your whole program exits or it is deleted using

    delete[] ar;
    

    note, that for delete you need the "[]" if and only if the corresponding new has had them, too.

提交回复
热议问题