Dynamic memory allocation

Submitted by:Jhon Smith

Date added:22 January, 2012

Category:C++

C++ example code for showing how to allocate and free memory

Tags: memory allocation

Code Snippet:

#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;
}
 
 

Comments