C++ New And Delete Question:
Download Job Interview Questions and Answers 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;
}
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