C++ new and delete

Question 1
How to create a dynamic array of pointers (to integers) of size 10 using new in C++? Hint: We can create a non-dynamic array using int *arr[10]
Cross
int *arr = new int *[10];
Tick
int **arr = new int *[10];
Cross
int *arr = new int [10];
Cross
Not Possible


Question 1-Explanation: 
Dynamic array of pointer having size 10 using new is created as,
int **arr = new int *[10]; 
So, option (B) is correct.
Question 2
Which of the following is true about new when compared with malloc. 1) new is an operator, malloc is a function 2) new calls constructor, malloc doesn't 3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type.
Cross
1 and 3
Cross
2 and 3
Cross
1 and 2
Tick
All 1, 2 and 3


Question 2-Explanation: 
Question 3
Predict the output?
#include <iostream>
using namespace std;

class Test 
{
  int x;
  Test() { x = 5;}
};

int main()
{
   Test *t = new Test;
   cout << t->x;
}
Tick
Compiler Error
Cross
5
Cross
Garbage Value
Cross
0


Question 3-Explanation: 
There is compiler error: Test::Test() is private. new makes call to the constructor. In class Test, constructor is private (note that default access is private in C++).
Question 4
What happens when delete is used for a NULL pointer?
 int *ptr = NULL;
 delete ptr; 
Cross
Compiler Error
Cross
Run-time Crash
Tick
No Effect


Question 4-Explanation: 
Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
Question 5
Is it fine to call delete twice for a pointer?
#include<iostream>
using namespace std;

int main()
{
    int *ptr = new int;
    delete ptr;
    delete ptr;
    return 0;
}
Cross
Yes
Tick
No


Question 5-Explanation: 
It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing.
There are 5 questions to complete.

  • Last Updated : 28 Sep, 2023

Share your thoughts in the comments
Similar Reads