c++ dynamic memory allocation using “new”

后端 未结 4 1957
温柔的废话
温柔的废话 2020-12-19 16:24

I\'m new to C++, trying to learn by myself (I\'ve got Java background).

There\'s this concept of dynamic memory allocation that I can assign to an array (for example

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 17:06

    if you wanna use an array and you dont know the exact size at the compile time, thats when dynamic memory allocation steps in. See the example below,

    int a[3] = {1,2,3};  //<= valid in terms of syntax;
    

    however,

    int size = 3;
    int a[size] = {1,2,3} //<= compile error
    

    in order to fix this,

    int* ArrayPtr = new int[size];
    

    also, when freeing it, call delete[] ArrayPtr; instead of delete alone, coz we are talking abt freeing a BLOCK of memory at this moment.

提交回复
热议问题