More Pointer Issues


Pointers are very different from other kinds of variables. Instead of holding actual data, they hold directions for getting to variables. Because of this, you can have a bunch of pointers that all are pointing to the same variable. When you change the variable in one, you're changing it in all of them! Take a look at this piece of code:

void main(void)
{
  int *nacho, *taco;

  nacho = new int;
  *nacho = 58;
  taco = nacho;

  cout << "I could eat " << *taco << " tacos!" << endl;
}

What do you think the output of that program is? Well, besides making the programmer hungry, the program spits out this message :

I could eat 58 tacos!

How did that work? Well, look at what the program is doing. After creating two pointers-to-int, it creates an int and assigns its location to nacho. ("nacho = new int") Then, the int pointed to by nacho is given the value 58. Now, here's the tricky part. The next line, "taco = nacho", is giving taco the location of nacho. Once you've assigned the location to taco, either of them can deal with the int you've created.


Table of Contents

Pointers | Pointer Operations | More Pointer Issues | Deleting Variables
Checking for Nothing | Exercises