Simple quiz on cpp

Let us see whether you can answer this memory allocation question on c++

To allocate memory for an integer in c++, you can use
  1. int *ptr = new int;
  2. int *ptr = new int(10);
  3. int a=12; int *ptr = new int(a+2);
  4. any of these






Answer : 4

All of these are valid methods of dynamic memory allocation in c++. 
  • First line allocates memory for an integer and the address of this integer is stored in ptr
  • Second line allocates memory for an integer and initializes this integer to 10. *ptr = 10
  • Third line allocates memory for an integer and initializes that integer to 12

Also note that

    int *ptr =new int[10]; 

is completely different, which allocate memory for an array of 10 integers. 


Comments

Popular Posts