C Programming How Pointers Work

Last modified by Microchip on 2023/11/09 09:06

Let's take a look at a very simple example of how pointers work. In this program fragment, there are two ordinary integer variables and one pointer to an integer. Note that in the pointer declaration, the * operator is used only to indicate that the variable p is a pointer to an int, not an in itself. Anywhere else in the code, this notation will mean something else, as we will see in a moment.


Pointers 1

The first line of code assigns the hex value 0xDEAD to the variable x, as we have seen in previous examples. When this code is compiled, we can look at the map file to see where x was located by the linker. Every time you compile a program, a map file will be generated by the linker to document where it placed the various elements of your program. When this example is compiled, we find that x was placed at 0x08BC.

Pointers 2

Next, we assign the hex value 0xBEEF to y. Using the map file as we did with x, we found that #y was located at address 0x08BE.

Pointers 3

Now, we start working with the pointer variable p. On this line, we assign the address of x to p by using the unary & (address of) operator in front of x. Note that the value stored in p is 0x08BC – this is the address of x (that we can verify with the map file). Now, we can say that p points to x.

Pointers 4

After initializing the pointer variable p, we can use it to access the data it points to. This line of code basically says assign the value 0x0100 to the variable pointed to by p. Also note that now, the * in front of p indicates that we want to use the location that p points to – not the location of p itself. Although the syntax of *p is the same as what we saw in its declaration, it has a different meaning: use the variable that is pointed to by p.

The net result of this operation is that the value of x is changed to 0x100. Since p{ contains the address of x, using *p is the same as using x.

Pointers 5

On this line, we change the value of the pointer p to contain the address of #y. So now, p points to y.

Pointers 6

Finally, we write the value 0x0200 to the variable pointed to by p which is y since that is what we just set it to. The net effect is that the value of y was changed to 0x0200. After changing p in the previous line, any time we use *p, it will be the same as if we used y.

Pointers 7