Dereferencing
Lesson outline
What is Dereferencing?
Dereferencing means accessing the value stored at the memory address a pointer holds. It is done using the dereference operator (*).
Key points:
- Translates a memory address into the actual value it points to
- Can be used for both reading and writing values (unless the pointee type is const)
- Dereferencing an invalid pointer (null, dangling, or out-of-bounds) leads to undefined behavior
Dereferencing Syntax
The * symbol appears in declarations to form pointer types and in expressions to dereference. In expressions, *ptr yields the referred-to object.
Practical Dereferencing Examples
Dereferencing is often used to modify values indirectly, to pass values by pointer to functions, and to walk arrays.
Member Access via Pointers
Use -> to access members through a pointer to an object. p->m is shorthand for (*p).m.
Operator Precedence Gotchas
*, prefix/postfix ++, and + have different precedences. Parentheses make intent explicit.
Const and void* Considerations
You cannot modify a value through a pointer-to-const.
void* is a generic, untyped pointer and cannot be dereferenced directly; cast it to the correct type first.
Common Dereferencing Pitfalls
- Dereferencing null pointers (
nullptr). - Dereferencing dangling pointers (pointing to destroyed or out-of-scope objects).
- Dereferencing uninitialized pointers (indeterminate value).
- Performing pointer arithmetic that leaves the array's bounds and then dereferencing.
- Forgetting parentheses in expressions like
(*p)++vs*p++(they do different things).