Dynamic Memory Allocation


  • There are cases where it would be useful to size or resize arrays while the program is being run.
  • Dynamic memory allocation allows us to allocate memory of whatever size we want when we need it.

Dynamically allocating single variables

  • With the new operator.
  • The new operator returns the address of the variable that has been allocated. This address can be stored in a pointer, and the pointer can then be dereferenced to access the variable.
  • After finishing with the dynamically allocated variable, we need to explicitly free the memory. This is done with the delete operator.
int *pnValue = new int; // dynamically allocate an integer
*pnValue = 7; // assign 7 to this integer
delete pnValue; 
pnValue = 0;

Dynamically allocating arrays

  • To allocate an array dynamically, we use the array form of new and delete.
int nSize = 12;
int *pnArray = new int[nSize]; //nSize does not need to be a constant
pnArray[7] = 7;
delete[] pnArray;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.