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?
This question is related to
c++
arrays
pointers
new-operator
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).
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"
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"
The statement basically does the following:
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];
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]
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];
Source: Stackoverflow.com