Dynamic memory allocation program in C code example

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

#include <iostream>
using namespace std;

int main () {
   double* pvalue  = NULL; // Pointer initialized with null
   pvalue  = new double;   // Request memory for the variable
 
   *pvalue = 29494.99;     // Store value at allocated address
   cout << "Value of pvalue : " << *pvalue << endl;

   delete pvalue;         // free up the memory.

   return 0;
}

Tags:

Cpp Example