Dynamic memory allocation code snippet

Summary

Source code of C++ program, showing how to allocate and free memory.

Source code

C++: dynamic_memory_allocation.cpp

#include <iostream>

 

using namespace std;

 

int main() {

      // declare pointer to int

      int *pInt;

 

      // allocate memory

      pInt = new int;

 

      // assign value using dereferencing

      *pInt = 5;

 

      // print that value

      cout << "*pInt: " << *pInt << endl << endl;

 

      // free memory

      delete pInt;

 

      // allocate memory to store three integers

      // (an array)

      pInt = new int[3];

 

      // assign three integers

      *pInt = 1;

      *(pInt + 1) = 2;

      *(pInt + 2) = 3;

     

      // print values using loop

      for (int i = 0; i < 3; i++)

            cout << "*(pInt + " << i << "): " << *(pInt + i) << endl;

 

      // free memory

      delete [] pInt;

 

      return 0;

}

 

Sample run

C/C++

*pInt: 5
 
*(pInt + 0): 1
*(pInt + 1): 2
*(pInt + 2): 3
 

Partners Ads

sewing thread