A Special Pointer Notation

Pointer variables can be included within structures. Here is an example of a structure which has a pointer variable in it:

struct friend
  {  string name;
     int age;
     parent *mother, *father;
  };

friend pal, cousin, neighbour;
friend *mate;
parent Deirdre, Sam, Angela, Fred;

This structure definition stores the friend's name and his/her age and two pointers to other objects, structures presumably, of type parent. Here is the code that sets up the values for the cousin variable:

cousin.name = "Colin";
cousin.age = 37;
cousin.mother = &Deirdre;
cousin.father = &Fred;

Alternatively, we might need a pointer to point to the structure. You will see that we have declared a pointer to friend structures, called *mate. The following code segment makes this pointer point to the pal variable.

mate = &pal;

(*mate).name = "Thomas";
(*mate).age = 22;
(*mate).mother = &Angela;
(*mate).father = &Sam;

In this case, *mate means "the object that mate points to", which is a structure. This is why we can follow *mate with a dot and the variable names that make up the structure.

You notice that you have to put brackets round the *mate part for the compiler to interpret it correctly. If you didn't, i.e. if you put *mate.name then the compiler would interpret it as *(mate.name), i.e. it would think that name was a pointer itself. Anyway, it would get in a terrible tangle.

C++ gives a short-cut way of writing this. Instead of using brackets and asterisks, you can write -> between the pointer and the field of the structure. Here is the same example, written using this short-hand notation:

mate = &pal;

mate->name = "Thomas";
mate->age = 22;
mate->mother = &Angela;
mate->father = &Sam;

Essentially, x->y means "x is a pointer that points to an object containing a variable called y. Refer to that variable". There is no reason why you can't use this notation on the right side of the assignment, for instance:

mate->name = cousin->name;

The right side of this refers to the variable name that is part of the structure pointed to by cousin (i.e. the string "Colin"). In this case, the name slot in the structure pointed to by mate is set to "Colin" as well (i.e. Thomas changes his name to Colin!)


Top of the page
Main Menu
Move on