Using a Pointer Variable

Once ptr points to val, we have two ways to access the int value stored in val. The usual way is direct, using the name of val:

printf( " val = %d\n", val );

The second way to access val is indirect, using the pointer variable ptr and the indirection operator:

printf( "*ptr = %d\n\n", *ptr );

Both of the preceding statements print the value of val, confirming that you can access the contents of val indirectly as well as directly. Once ptr points to val you can use *ptr anywhere that you would use val.

Summary: The indirection operator can obtain the value to which a pointer points.

Using the indirection operator to access the contents of val is the second use of this operator (the first is in declaring pointer variables, as explained earlier). When the asterisk appears in front of the name ptr, the expression states that you want to use the value the pointer points to, not the value of ptr itself.

The second printf statement in POINTER.C uses the expression *ptr to access the value stored in val.

This use of a pointer is analogous to the PEEK function in QuickBasic. You can just as easily use ptr to change the data in val, an operation that somewhat resembles a QuickBasic POKE statement.

For instance, if you add the following statements to the end of POINTER.C,

*ptr = 3301;

printf( "%d\n", val );

the program prints 3301.

Figure 8.3 shows the relationship between ptr and val after executing the previous two statements.

As Figure 8.3 shows, the value stored in val has changed from 25 to 3301. The contents of val were changed indirectly, through the pointer ptr.