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

后端 未结 8 1172
生来不讨喜
生来不讨喜 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:31

    The statement basically does the following:

    1. Creates a integer array of 'n' elements
    2. Allocates the memory in HEAP memory of the process as you are using new operator to create the pointer
    3. Returns a valid address (if the memory allocation for the required size if available at the point of execution of this statement)
    0 讨论(0)
  • 2020-12-03 05:35

    new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int.

    The pointer will then store the address to this block of memory.

    But be careful, this allocated block of memory will not be freed until you tell it so by writing

    delete [] array;
    
    0 讨论(0)
  • 2020-12-03 05:36

    It allocates that much space according to the value of n and pointer will point to the array i.e the 1st element of array

    int *array = new int[n];
    
    0 讨论(0)
  • 2020-12-03 05:38

    The new operator is allocating space for a block of n integers and assigning the memory address of that block to the int* variable array.

    The general form of new as it applies to one-dimensional arrays appears as follows:

    array_var = new Type[desired_size];
    
    0 讨论(0)
  • 2020-12-03 05:44
    int *array = new int[n];
    

    It declares a pointer to a dynamic array of type int and size n.

    A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array. Also, since the memory is dynamically allocated using new, you've to deallocate it manually by writing (when you don't need anymore, of course):

    delete []array;
    

    Otherwise, your program will leak memory of at least sizeof(int) * n bytes (possibly more, depending on the allocation strategy used by the implementation).

    0 讨论(0)
  • 2020-12-03 05:47

    It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"

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