Create Pointers
Lesson outline
Pointer Fundamentals
Pointers are objects that store the memory address of another object (or nullptr). They enable indirect access and are essential for dynamic memory, polymorphism, and interfacing with low-level APIs.
Key characteristics:
- Store memory addresses
- Have their own address and size
- Can be reassigned to point somewhere else
- Can be
nullptr(points to no object) - Must be dereferenced to access the pointed-to value (and only if not null)
Pointer Declaration Syntax
Use * in the declarator to declare a pointer; use & (address-of) to take a variable's address. Place the * next to the identifier to avoid confusion.
Be careful when declaring multiple variables in one statement: only the names with * are pointers.
Pointer Initialization Examples
Pointers can be initialized with the addresses of variables or arrays. When printing a char* address, cast to const void* to avoid it being treated as a C-string.
Dereferencing and Member Access
Use *ptr to read/write the value, and -> to access members through a pointer to an object.
Pointer Arithmetic (Arrays)
Pointer arithmetic advances by element size. Incrementing an int* moves by sizeof(int) bytes.
Null & Dangling Pointers
Always initialize pointers. A dangling pointer points to an object that no longer exists (e.g., after delete or the end of a variable's lifetime).
Pointer Size and Architecture
For a given target and ABI, all object pointers typically have the same size (e.g., 4 bytes on many 32-bit platforms, 8 bytes on many 64-bit platforms). Exact sizes are implementation-defined and may differ on embedded systems; function-pointer size can also differ.