Pointers


C++ uses pointers very much like Pascal does; The differences, more often than not, are very small. Let's look at how to declare pointers in both Pascal and C++:

Pascal :

 p : ^Integer;
C++ :

 int *p;

In both cases, the difference between declaring an integer and a pointer that points to an integer (we'll say "pointer-to-int" from now on) is a single character. It is important that you notice that in Pascal, you're declaring p to be of type pointer-to-int, while in C++, you're declaring a pointer whose type is int. The difference? If you declare many pointers on one line in C++, you must make sure to put a * by each of the variables. Also, you can put ints next to pointers-to-ints in a declaration by not putting a * next to the int. Confused? Try reading some of the next examples, and see if they help visualize the concepts.

Here are some more examples of declaring pointers:

Mmm..Taco
int *taco, *nacho;

char burrito, *salsa;

float *chimichanga, margarita;

Notice that you can put both variables and pointers-to-variables on the same line? On the second line, both a character (burrito) and a pointer-to-character (salsa) were both declared. On the third line, a pointer-to-float (chimichanga) and a float (margarita) were both declared.

Watch Out!

It's easy to see the line

float * chimichanga, margarita;
and think that you are declaring chimichanga and margarita both to be of type pointer-to-float. This is NOT the case, however. The * only applies to the variable it's right in front of, in this case chimichanga. By making your *'s touch the front of your variables, you can avoid this mistake. Here's what the improved, easier-to-understand version looks like:

float *chimichanga, margarita;

However, if you wanted to declare two pointers-to-float, this is what it looks like:

float *chimichanga, *margarita;

Notice that they both must have *'s next to them, so C++ knows they are pointers. Here's what it looks like in Pascal:

chimichanga, margarita  : ^real;


Table of Contents

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