dynamic memory allocation c++ code example

Example 1: c++ delet from memory

// Delete pointer
int* ptr1 = new int;
delete ptr1;

// Delete array
int* array = new int[10];
delete[] array;

Example 2: dynamic memory allocation

int *p = new int; // request memory
*p = 5; // store value

cout << *p << endl; // Output is 5

delete p; // free up the memory

cout << *p << endl; // Output is 0

Example 3: c++ delete dynamically allocated array

int length = 69;
int * numbers = new int[length];
delete[] numbers;

Example 4: 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 5: dynamic memory allocation in c++

char* pvalue  = NULL;         // Pointer initialized with null
pvalue  = new char[20];       // Request memory for the variable

Example 6: dynamic memory management c++

// declare an int pointer
int* pointVar;

// dynamically allocate memory
// using the new keyword 
pointVar = new int;

// assign value to allocated memory
*pointVar = 45;

Tags:

Cpp Example