1. Computing & Technology

Discuss in my forum

C++ Tutorial - About Pointers

By , About.com Guide

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

©2012 About.com. All rights reserved.

A part of The New York Times Company.