Passing Pointers


Here's a little background info on passing to function. When you call a function, all the parameters you send to it are copied and given to the function to use. This means that if a function makes changes to the variables it is given, they won't be changed anywhere but inside that function. For instance, look at the following code:

#include <iostream.h>

void change_values(int a, int b)
{
  a = 4;
  b = 5;
}

void main(void)
{
  int a;
  int b;

  a = 1;
  b = 2;

  change_values(a,b);

  cout << "A is " << a << ", B is " << b << "\n";
} 

Here's the output of this program:

A is 1, B is 2

Note that the call to change_values did not change the variables sent to it. Why? Because the function changes copies of what was passed to it. So, the question is, how do we get functions to be able to change things we pass to them? The answer is:

Don't give a function data, give a function pointers to data.

So how can we do that? Well, remember that the & operator gives you the address of where a variable is inside your computer; or more to the point, it gives you a pointer to the data. Armed with this knowledge, let's redo the above program:

#include <iostream.h>

void change_values(int *a, int *b)
{
    *a = 4;
    *b = 5;
} 

void main(void)
{
  int a;
  int b;

  a = 1;
  b = 2;
 
  change_values(&a,&b);

  cout << "A is " << a << ", B is " << b << "\n";
}

And behold! The gods of C++ smile, and you are presented with:

A is 4, B is 5

Take a look at the above code, and make sure you understand what's going on. The main function passes the address of a and b this time, so the function change_values is passed a copy of the addresses. Using the addresses of a and b, change_values can access their data directly. Think of this concept as calling someone you to give directions to where they left their lunch. Using those directions, you could pick up their tasty enchiladas, and using the same idea, change_values can get to those tasty variables, a and b. You may remember this whole idea as using the VAR parameter in Pascal to pass the real variable instead of a copy.


Table of Contents

Parameter Passing | Passing Pointers | Passing Arrays | Reference Variables
Exercises