Pointers: Addresses and Dereferencing
Reach a value through its address
The string comparisons distinguished matching text from matching addresses. Now we will use an address to reach one existing value. This gives us a way to update that value without making a separate copy.
An object is a region of storage holding a value, such as the integer variable count. Its address identifies that object in memory. A pointer holds an address value; the object it points to is sometimes called its pointee.
After declaring count, int *location = &count; gives location the address of count. The * in the declaration makes this an int pointer; later, *location means the integer at that address. Reading or assigning through it reaches count itself, not a separate copy. Always initialize a pointer before dereferencing it; an uninitialized pointer does not identify an object you can use.
The first print reads through the pointer. The assignment through *location changes count, so the second print sees the new value. The address stored in location stays the same:
#include <stdio.h>
int main(void) {
int count = 3;
int *location = &count;
printf("Before: %d\n", *location);
*location = 5;
printf("After: %d\n", count);
return 0;
}
There are two objects: count stores an integer, and location stores a pointer value. The expressions count and *location access the same integer object. Updating *location changes that integer; it does not replace the address stored in location.
Address, pointee, and lifetime
The diagram shows &count rather than a numeric address because the address can differ between runs. At each dereference, location must still point to a live int. Making up a numeric address does not make a usable pointer. All addresses in these diagrams are symbolic labels, not observed numeric addresses. If you need to print an object pointer in C, use %p with a (void *) conversion, not %d; the exact printed address is implementation-dependent, so these exercises check the pointed-to values instead.