int *arr = new int(10);
int *arr = new int[10];
It is the code of dynamic memory allocation in c++. But I am not getting What is the difference between these two.
int *arr = new int(10);
int *arr = new int[10];
It is the code of dynamic memory allocation in c++. But I am not getting What is the difference between these two.
int *arr = new int(10);
allocates heap memory for a single integer, initialized to 10.
int *arr = new int[10];
allocates heap memory for an array of 10 integers, none of which are initialized to any specific value.
For a simple example, let's talk about what happens on the stack.
int x(10)
This generally means assigning an value to an int
named x
.
int x[10]
This generally means creating an array named x
of 10 elements.
So, when it come to dynamic memory, it's the same thing.
int* x=new int(10)
This creates a single integer on the heap and assigns it the value 10.
int* x=new int[10]
This creates an array of 10 integers on the heap.
Keep it in mind: The ( )
and { }
mainly used for initialization in declarations. And [ ]
is mainly an indexing operator. So in the first statement, you are trying to allocate an int
memory with 10
as the initial value. And in the second statement, you are trying to allocate a 10 int
block array with no default initialization.