7.1 Pointer Basics
Every variable occupies a block of memory, and each block has an address, usually written in hexadecimal such as 0x0060FEFC. A pointer is a variable whose job is to store an address.
Address-of and declaring a pointer
& is the address-of operator and gives the address of a variable; * declares a pointer. The %p placeholder prints an address in hexadecimal.
int data = 3;
int *p = &data; // p stores the address of data
printf("%d\n", data); // 3
printf("%p\n", &data); // the address of data
printf("%p\n", p); // the same as &dataRead int *p as "p is a pointer to an int." p holds an address, and &data is the address of data.
Dereferencing
A pointer holds the address of another variable, so you can follow that address to reach the variable. Putting * in front of a pointer is called dereferencing; it can both read and write the pointed-to value.
printf("%d\n", *p); // dereference to read: 3
*p = 5; // modify data through the pointer
printf("%d\n", data); // 5*p = 5 does not change p (it still points to data); it changes the value of data to 5.
NULL and wild pointers
If a pointer is declared without initialization, it points to an undefined address. Such a pointer is called a wild pointer, and dereferencing it is undefined behavior that often crashes the program.
When a pointer has no valid target yet, set it to the null pointer NULL and check before dereferencing:
int *q = NULL;
if (q != NULL) {
printf("%d\n", *q); // dereference only when not null
}Make a pointer point to valid memory before using * — this is the most basic safety habit with pointers.