What is the difference between these two declarations :

  • int *p = new int;
  • int *q;

2 Answers

0
eerorika On
int *p = new int;

This is a declaration. It declares a variable of type int *. The name of the variable is p. The variable is copy-initialised with the expression new int.

int *q;

This is a declaration. It declares a variable of type int *. The name of the variable is q. The variable is default initialised.

1
Walter On
 int *p = new int;
 *p = 8;

The first statement declares a new variable p to be a pointer to int and initialises it with the address returned by new int, which is a valid memory address for storing an int. The second statement assigns the value 8 to the int at the memory address pointed to by p.

int *q;
*q = 8;

Now the first statement does not initialize the pointer q, which will hence have no meaningful value. The second statement then attempts to write to a memory address which in all likelihood is not an address where such an operation is allowed and as a result the program will crash (most likely with segmentation fault).