C++ New And Delete Question:
Download Questions PDF

What is dynamic memory management for array?

Answer:

Using the new and delete operators, we can create arrays at runtime by dynamic memory allocation. The general form for doing this is:

p_var = new array_type[size];
size specifies the no of elements in the array
To free an array we use:
delete[ ]p_var; // the [ ] tells delete that an array is being freed.

Consider following program:
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
try
{
p = new int(10); //allocate array of 10 integers
}
catch (bad_alloc x)
{
cout << “Memory allocation failed”;
return 1;
}
for (i = 0; i < 10; i++)
p[i] = i;
for (i = 0; i < 10; i++)
cout <<p[i]<<”\n”;
delete [ ] p; //free the array
return 0;
}

Download C++ New And Delete Interview Questions And Answers PDF

Previous QuestionNext Question
What is new operator and delete operator?Following is the not a correct statement for preprocessor directive declaration?

a) #include<iostream.h>
b) #include<iostream.h> #define LEFT 1
c) #define LEFT 1
d) #define ABS(a) (a)<0 ? -(a) : (a)