C++ Learning Resource Network!

 C++ Tutorials  >  Pointers in C++  >  Dynamic Memory Allocation

The main drawback of arrays is that the size of the arrays is fixed and it needs to be specified at compile time. Memory can be allocated and deallocated dynamically by using the new and the delete operators.

new Operator

Pointers provide the necessary support for C++'s powerful dynamic memory allocation systme. Dynamic allocation is the means by which a program can obtain memory while it is running.

In the programs discussed in the earlier sections, it is necessary to decalre arrays to some approximate size. It is not always possible to predict the size of the array and therefore in many cases it can lead to wastage of memory if the amount of data is much less than the maximum. It would be desiable to start the program and then allocate memory as the need arises. This capability is provided by the new operator.

The syntax for the new operator is:

<variable> = new <type>;

where <variable> is a pointer variable and <type> can be char, int, float or any user defined data type. The type of variable mentioned on the left hand side and he type mentioned on the right hand side should match. Consider the following examples:

char *cPtr;
cPtr = new char[10];

The above declaration allocates ten bytes to the pointer cPtr.

int *iPtr;
iPtr = new int;

This declaration allocates four bytes of memory and assigns the starting address to iPtr. The syntax of the new operator can also be modified to allocate memory of varying requirements. For example,

char *cPrt;
cPtr = new char[5];

allocates five bytes of memory and assigns the starting address to cPtr.

delete Operator

The delete operator is used to release the memory, which was allocated, using the new operator.

The syntax of the delete operator is:

delete <variable>;

where <variable> is a pointer variable.

Consider the following example:

char *pS;
pS = new char[10];
delete pS;

The above code releases the allocated memory to the pointer pS.


| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.