Welcome guest! Click here to register or login.
logo

<< Tutorial 15
Tutorial 17 >>

Dynamic Memory in C++

***Please register FREE to rate this tutorial***


Topics
Operators new & new[]
Operators delete & delete[]
Examples
Example 1

In C++, lets say you have the following scenario. Say that you want the user to enter a certain amount of numbers into an array. Seems like this will work (as a snippet):

int x = 0;
cout << "Enter the amount of numbers you want to use: ";
cin >> x;

int arr[x] = {0};

WRONG! The compiler will not allow this to occur as it does not know the FIXED size of the integer x (since an array is a fixed memory block).

There is a solution: dynamic memory allocation.

Operators new & new[]

There is an operator called new OR new[] which will allocate memory from what is called the heap of a program. They are defined as follows:

	type *pointerName = new type;
	type *pointerName = new type[ size ];

Where the first line above declares an individual element of a given type (such as int, float, char) and the second element declares multiple elements of a given type in the form of an array. In either condition, the pointer must be of the same type. What is returned from the allocation is the address of the first element in the array or individual item.

Let's see a short program that will demonstrate this:

Example 1:
Sample program

Download source code here (Right click - Save Tagret As...)

#include <iostream>
using namespace std;

int main(){

	int x = 1;

	cout << "Enter the size of the dynamic array: ";
	cin >> x;

	while(x <= 0){
		cout << "Invalid entry.  Try again: ";
		cin >> x;
	}

	int* p = new int[x];

	for(int i = 0; i < x; i++){
		cout << "Enter p[" << i << "]: ";
		cin >> p[i];
	}

	cout << "Thank you!" << endl;

	for(i = 0; i < x; i++)
		cout << p[i] << " " << endl;

	return 0;
}

What this program allows us to do is enter the size of a new integer array and enter values into that new array. It will then output what was entered.

Operators delete & delete[]

Paired with new and new[] is delete and delete[]. This will remove (delete) all the space that was dynamically created and allow it to be used again. This is defined as follows:

	delete pointerName;
	delete[] pointerName;

Where you must choose the correct one above to use. If you dynamically created an array then use the second, otherwise use the first. In the above example, this snaippet will show you how to remove the memory:


<< Tutorial 15
Tutorial 17 >>