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

C++ Tutorial - About Pointers

By David Bolton, About.com

8 of 10

Some Rules for Working with Pointers

Some Rules with Pointers

These are more common sense than hard and fast rules.
  • Always initialize pointer variables.
  • If you use C strings, never forget to include the terminating '\0' when calculating the storage size.
  • Check that new doesn't generate an exception or return 0.
  • For every new there is an equal and opposite delete()!
  • For arrays you must use the [] for both new and delete. Don't free with delete() something allocated with new()[] and vice versa.
  • After you've deleted a pointer, set it to 0.
For example.
int * pint=new int ;
/*
Do something with pint
*/
delete pint ;
pint = 0;
Setting pint to 0 is a safety feature. Just because the memory has been released by the call to delete() does not prevent it accidentally being reused. This could lead to a nasty bug but delete() does nothing with a 0 value pointer.

New is more than just malloc()

You might be wondering why not just malloc(), especially if you know C. Two reasons
  1. new is typesafe. Whereas malloc() returns a void *, new returns an object of the specified type.
  2. malloc() does not initialise memory whereas new calls a constructor on an object.
Example 3 shows a struct being created.
// ex3.cpp

#include <iostream>
using namespace std;

struct s{
  int a;
  double d;
  s() {a =9;d=9.999;}
};

int main(int argc, char* argv[])
{
  s * value = new s;
  cout << "Value of value.a = " <<
   value->a << " value.d = " << value->d << endl;
  return 0;
}

The output from this is:
Value of value.a = 9 value.d = 9.999
Download Example 3.

This shows that the constructor s() was called.

On the next page : More examples of 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. Some Rules for Working with Pointers

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

All rights reserved.