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

C++ Tutorial - About Pointers

By , About.com Guide

9 of 10

Some More Examples of Pointers in C++

Example 4 doesn't use pointers. I wanted to make the point that if you can, use references where possible. They are safer than pointers. This is a rewrite of Example 5 in the C tutorial which used pointers, so you can see how C++ references not only shorten but simplify code.
// ex4.cpp
//
#include <iostream>
using namespace std;

#define maxitems 1000
typedef int vector[maxitems];

void addvectors(vector & temp,vector & v1,vector & v2) {
  for (int index =0;index < maxitems;index++)
    temp[index]= v1[index] + v2[index];
  }

int main(int argc, char* argv[])
{
  vector a,b,c;
  int index;
  for( index=0; index < maxitems; index++){
   a[index]=10+index;
   b[index]= index*1000;
  }
 addvectors(c,a,b) ;
 cout << "c[0]= " << c[0] << "\nc[999]= " << c[999] << endl;
 return 0;
}
Download Example 4

The output from this is

c[0]= 10
c[999]= 1000009
This passes references to three arrays, each holding 1,000 ints and defined by the typedef vector. It loops through all elements, adding each of the elements and storing the result in the third.

On the Next Page : A more complex example.

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Some More Examples of Pointers in C++

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

All rights reserved.