dynamic memory allocation in cpp code example
Example 1: dynamic memory allocation
int *p = new int;
*p = 5;
cout << *p << endl;
delete p;
cout << *p << endl;
Example 2: c++ delet from memory
int* ptr1 = new int;
delete ptr1;
int* array = new int[10];
delete[] array;
Example 3: what is dynamic memory allocation in c++
In the dynamic memory allocation the memory is allocated during run time.
The space which is allocated dynamically usually placed in a program segment which is known as heap.
In this, the compiler does not need to know the size in advance.
In C++, dynamic memory allocation means performing memory allocation manually by programmer.
It is allocated on the heap and the heap is the region of a computer memory which is managed by the programmer using pointers to access the memory.
The programmers can dynamically allocate storage space while the program is running but they cannot create a new variable name.
Example:
Example 4: dynamic memory allocation in c++
char* pvalue = NULL;
pvalue = new char[20];
Example 5: dynamic memory management c++
int* pointVar;
pointVar = new int;
*pointVar = 45;
Example 6: dynamic memory allocation in c++
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL;
pvalue = new double;
*pvalue = 29494.99;
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue;
return 0;
}