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

124,770

Solution 1

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;

Solution 2

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 should 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).

Solution 3

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)

Solution 4

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"

Solution 5

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];
Share:
124,770
pauliwago
Author by

pauliwago

Updated on November 07, 2021

Comments

  • pauliwago
    pauliwago over 2 years

    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 creating a pointer named array that's pointing to a new object/array int? Would someone care to explain?