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
The statement basically does the following:
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;
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];
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];
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).
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"