Pointer Operations


Let's try using pointers in a small program. Take a look at this piece of code:

void main(void)
{
  int *nacho;      /* Declare the pointer-to-int       */

  nacho = new int; /* Give nacho something to point at */
  *nacho = 42;     /* Assign what nacho points to 42   */

  cout << "I feel like I could eat " << *nacho << " nachos!" << endl;
}

Let's go over what each line does. First, we say "int *nacho;", creating a pointer-to-int named "nacho". Then, we say "nacho = new int;". What does that do? Well, the part that says "new int" is creating an int in memory, and then, much like a function would, it returns the location of the integer it created. This location is then assigned to "nacho". The equivalent statement in Pascal would be :

new(nacho);

Now that nacho has the location of the new integer we've created, we can start assigning it values. The third line, "*nacho = 42;", is almost the same as saying "assign the integer pointed to by nacho 42". Remember, nacho is the location of the integer, and *nacho is the actual integer. Don't get them mixed up!

The last line is another example of working with the value that's pointed at. Notice that we're printing *nacho, the integer, not nacho, the location of the integer.


Table of Contents

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