Pointers to Structures

As you have probably seen, we can use a pointer to any data type, or even to a function. If you think about this for just a moment it makes sense. Everything in your program is loaded into memory. A pointer is simply an indicator of an address in memory. Your variables are places in memory, other pointers are referencing a place in memory, and functions are loaded in memory. Because all this is at some location in memory, it makes sense that you should be able to have a pointer variable that references that location in memory.

Because a structure is a complex data type, you can also have a pointer to a structure variable. In fact, pointers to structures are a commonly used technique. Recall from Chapter 7, when we first discussed structures, that a structure variable allows you to pass several pieces of data, and allows the function to return several pieces of data. A pointer to a structure allows you to point to that space in memory, just as you would point to any other variable’s space in memory.

There is one slight change when dealing with pointers to structures. Normally you access an element of a structure by giving the structure name, a (.), then the name of the element. For pointers to structures you must use a -> rather than a pointer. Let’s examine an example that should clarify this.

Example 9.4

Step 1: Write the following code into your favorite text editor.

#include <iostream> using namespace std;   struct account {   int accountnum;   float balance;   float interestrate; }; int main() {   account myaccount;  account *ptraccount;  //set the balance of the structure  myaccount.balance = 1000;  //initialize the pointer  ptraccount = &myaccount;  //change the pointers balance  ptraccount->balance = 2000;  //print out the structures balance cout << myaccount.balance << "\n";  return 0; } 

Step 2: Compile the code.

Step 3: Run the program. You should see something similar to Figure 9.5.

click to expand
Figure 9.5: Pointers to structures.

It is important to note, in this example, that when you change an element of the pointer to the structure, you are actually changing the element of the structure itself. This is because, like all points, a structure pointer is simply redirecting any commands or operations to the address in memory it points to.

C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net