c++ dynamic memory allocation using “new”

后端 未结 4 1958
温柔的废话
温柔的废话 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

    When you know the size of an array at compile time you can declare it like this and it will live on the stack:

    int arr[42];
    

    But if you don't know the size at compile time, only at runtime, then you cannot say:

    int len = get_len();
    int arr[len];
    

    In this case you must allocate the array at runtime. In this case the array will live on the heap.

    int len = get_len();
    int* arr = new int[len];
    

    When you no longer need that memory you need to do a delete [] arr.

    std::vector is a variable size container that allows you to allocate and reallocate memory at runtime without having to worry about explicitly allocating and freeing it.

    int len = get_len();
    std::vector v(len); // v has len elements
    v.resize(len + 10); // add 10 more elements to the vector
    

提交回复
热议问题