You declare a pointer variable by stating the type of the variable, the fact that it's a pointer, and the name of the variable. Here's an example: int *anIntPointer; int anInt = 100; The variable anIntPointer points at integers, as the type name int indicates. The asterisk indicates that the variable is a pointer to integers rather than a variable that contains integers. The second variable declaration does not have the asterisk, so anInt is a variable that contains an integer. You store an address in a variable with the ampersand operator, like this: int *anIntPointer; int anInt = 100; anInputPointer = &anInt; The third of these three statements stores the address of anInt into the pointer variable anInputPointer. As a result, the variable anIntPointer points to the location in memory where anInt resides. Figure 11.1 represents this graphically. Figure 11.1. Storing an address in a pointer variable.
In Figure 11.1, the pointer is represented by an arrow. The arrow is a graphical way of depicting the fact that the pointer variable anIntPointer stores the address of anInt. Your program can access the data in anInt through the pointer. To do so, you use the asterisk operator. Listing 11.1 gives a short example of how this is done. Listing 11.1. A program with a pointer
Line 8 of Listing 11.1 declares an integer variable and stores a 5 in it. Line 9 creates an integer pointer (a pointer to an integer) and sets it to point to the variable anInt. Line 11 prints the value in anInt, which is 5. On line 12, the program prints the value in the location that anIntPointer points to. Because anIntPointer points to anInt, the statement on line 12 prints the 5 again.
Line 15 of Listing 11.1 stores the value 100 in the location that anIntPointer points to. The statements on lines 1718 prove that doing so changes the value in anInt because anInt and anIntPointer both refer to the same memory location. This is proven again on lines 2125. The assignment statement on line 21 stores a 50 in anInt. The statements in lines 2324 show that this changes both anInt and *anIntPointer because both anInt and *anIntPointer refer to the same memory location. Is this confusing? If it is, you're having a very normal experience. Pointers are hard to learn. We all struggle with them when we first encounter them. You'll become proficient at them through practice, practice, and more practice. Anyone can master pointers and everyone feels frustrated with them at first. If you're wondering whether learning pointers is worthwhile, the answer is a big YES. I'll show you why shortly. However, before diving into that, I just want to quickly review what I've presented so far.
These four points are what you need to know to declare and use pointers. |