1
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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

3 Answers3

5

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.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
5

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Agent_A
  • 120
  • 1
  • 10
  • 2
    Handy reading: [Why are the terms “automatic” and “dynamic” preferred over the terms “stack” and “heap” in C++ memory management?](https://stackoverflow.com/questions/9181782/why-are-the-terms-automatic-and-dynamic-preferred-over-the-terms-stack-and) – user4581301 Aug 23 '21 at 15:21
  • @user4581301 thanks gotta read that thing tomorrow – Agent_A Aug 23 '21 at 15:33
1

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.

Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32