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. C++ streams can print an address directly.
int data = 3;
int *p = &data; // p stores the address of data
std::cout << data << std::endl; // 3
std::cout << &data << std::endl; // the address of data
std::cout << p << std::endl; // 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.
std::cout << *p << std::endl; // dereference to read: 3
*p = 5; // modify data through the pointer
std::cout << data << std::endl; // 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 nullptr and check before dereferencing:
int *q = nullptr;
if (q != nullptr) {
std::cout << *q << std::endl; // dereference only when not null
}Make a pointer point to valid memory before using *; this is the most basic safety habit with pointers.