1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - About Pointers

By David Bolton, About.com

7 of 10

An Example Using New and Delete

Example 2 below demonstrates allocating memory with new and freeing it with delete.
// ex2.cpp
//
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{

  int * a= new int[10];
  int * b=new int(89) ;
  cout << "*b=" << *b << endl;
  
  int * c = new (nothrow) int [1000000000];
  if (!c)
    {
       cout << "Failed to allocate memory" << endl;
    }

  *(a+5)=9;
  cout << "a[5]=" << *(a+5) << endl;
  delete [] a;
  delete b;
  delete [] c;
  return 0;
}
Download Example 2

The array a is allocated space for 10 ints but arrays cannot have an initial value. The int pointer b is allocated space for an int and given an initial value of 89. Next, there is a doomed attempt to allocate a billion ints on my 1GB RAM PC. As an int takes 4 bytes that would require 4GB. Also under 32 bit Windows you are limited to 2GB of RAM.

The (nothrow) prevents an exception occurring and the failed message is almost certain to be displayed, unless you are blessed with a 64 Bit computer and a surfeit of RAM.

The array a is tested by setting and displaying an array element. Just as in C, an array and a pointer can be considered the same-they are addresses. Adding 5 to the pointer is the same as indexing an array by [5].

Finally the three delete statements free up allocated memory. In the case of the filed c variable, freeing up a zero pointer is ok. Note the use of [] for a and c. Forget those on array pointer variables (even char *) and you will experience memory problems.

On the next page : Some Rules for using Pointers

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. An Example Using New and Delete

©2009 About.com, a part of The New York Times Company.

All rights reserved.