What is the difference between () and [] dynamic allocation?

Can anyone explain the difference between the following two forms and what they do:

int *p = new int[5]; 

      

and

int *p = new int(5);

      

Query

1) What do we allocate in both cases ie either an integer or an array?

2) What will be the initial value after selection in both cases?

3) And a link from where I can find about it

+3


source to share


5 answers


The syntax for the new expression is as follows:

  • keyword new

  • optional arguments enclosed in parentheses
  • type
  • optional initializer


The new int[5]

type int[5]

and initializer are missing. So an array of 5 is allocated int

, they are not initialized, and a pointer to the first element is returned.

In a new int(5)

type int

, and an initializer (5)

, so one is allocated int

, it is initialized with a value of 5 (as in int x(5);

), and a pointer to it is returned.

+10


source


int *p = new int[5];

      

allocates an "array" of integers with length 5. It returns a pointer to the beginning of 5 contiguous blocks of memory, each of which can contain int

.



int *p = new int(5);

      

allocates a pointer to a single integer, initialized to 5.

+6


source


In the first case, it allocates an integer array of size 5. In this case, the elements in the array are not initialized.

In the second case, it allocates one integer with the value 5.

Links:

http://www.cplusplus.com/reference/new/operator%20new/ http://www.cplusplus.com/reference/new/operator%20new:5/

+3


source


here i will answer all questions one by one

Question 1: What do we allocate in both cases ie either an integer or an array?

int *p = new int[5]; // you are allocating an array
int *p = new int(5); // you are allocating an integer

      

Question 2: What will be the initial value after selection in both cases?

int *p = new int[5]; // Initially there will be random value on all indexes
int *p = new int(5); // Initially value will be 5

      

Question 3: And a link from where can I find about this?

Check the following links

http://www.cplusplus.com/doc/tutorial/dynamic/

http://en.wikipedia.org/wiki/Initialization_%28programming%29

+3


source


Square brackets are used to denote arrays of its elements. So in this statement

int *p = new int[5];

      

Here an array of 5 integer elements is allocated that are not initialized. Compare with definition

int a[5];

      

In this statement

int *p = new int(5);

      

an object of type int is allocated, which is initialized 5. Compare it with the following definition

int x = int( 5 );

      

or simply

int x = 5;

      

+2


source







All Articles