Pointing to Structures


Structures are fairly easy to grasp, but they do have one other small trick to them -- when you're using Pointers-to-structures.

Say we create a pointer-to-structure named enchilada. After creating memory and assigning it to enchilada, we're ready to play around with it. Here's where the weird part comes in -- when you're accessing variables from a pointer-to-structure, you use "->" instead of ".". To access a variable named tasty inside the structure pointed to by enchilada, you say:

enchilada->tasty

The -> tells C++ that you want to access the element tasty, which is in a struct that enchilada points to. This is a replacement for the long and very icky version, shown below:

(*enchilada).tasty

If you're a little unsure of that code, heres what it's saying in a breakdown:

  1. enchilada is a pointer to the structure.
  2. (*enchilada) is the structure.
  3. (*enchilada).tasty is the field tasty inside the structure.
The key point is that "->" saves you time and confusion.


Table of Contents

Structures | Pointing to Structures | Using Pointers to Structures | Using Escape Codes
Shortcuts | Exercises