1. Technology

C++ Tutorial - About Pointers


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++){
    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.

©2014 About.com. All rights reserved.