int *array = new int[n]; what is this function actually doing?

后端 未结 8 1173
生来不讨喜
生来不讨喜 2020-12-03 05:00

I am confused about how to create a dynamic defined array:

 int *array = new int[n];

I have no idea what this is doing. I can tell it\'s c

相关标签:
8条回答
  • 2020-12-03 05:51

    As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr:

    std::unique_ptr<int[]> array(new int[n]);
    

    This creates a smart pointer to a memory block large enough for n integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array; statement.

    Another (probably preferred) option would be to use std::vector if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:

    std::vector<int> array;
    array.push_back(1);  // adds 1 to end of array
    array.push_back(2);  // adds 2 to end of array
    // array now contains elements [1, 2]
    
    0 讨论(0)
  • 2020-12-03 05:54

    In C/C++, pointers and arrays are (almost) equivalent. int *a; a[0]; will return *a, and a[1]; will return *(a + 1)

    But array can't change the pointer it points to while pointer can.

    new int[n] will allocate some spaces for the "array"

    0 讨论(0)
提交回复
热议问题