Pointers and Memory Management
Pointer Arithmetic
Navigating memory with pointers — how pointer math works and when to use it
Interview: Low-level programming and array algorithms
Pointer Arithmetic
Pointer arithmetic lets you navigate memory by adding or subtracting integer offsets from pointer values. Unlike regular integer arithmetic, pointer arithmetic is type-aware: adding 1 to an int* advances the pointer by sizeof(int) (4 bytes), not 1 byte. This is why iterating arrays with pointer arithmetic works naturally.
Valid Operations
- Pointer + integer: advance pointer by n elements.
- Pointer - integer: move pointer back by n elements.
- Pointer - Pointer: returns the element count between two pointers (type:
ptrdiff_t). Only valid for pointers into the same array. - Comparison (<, >, ==): valid for pointers into the same array.
Undefined Behavior with Pointer Arithmetic
Pointer arithmetic is only defined within array bounds (plus one-past-the-end). Going outside these bounds — even without dereferencing — is undefined behavior. Comparing or subtracting pointers from different arrays is also undefined.
Interview Corner
Q: What does incrementing a char vs int by 1 do to the address?
A: char*: address increases by 1 byte (sizeof(char) = 1). int*: address increases by 4 bytes (sizeof(int) = 4 on most platforms). This is the key property of type-aware pointer arithmetic — it always steps by one element, regardless of element size.
Common Pitfalls
- Out-of-bounds arithmetic: Even computing a pointer outside the array (without dereferencing) is undefined behavior, except for one-past-the-end.
- Casting to char for byte-level access: Allowed (char can alias any type), but manipulating object bytes directly can break object invariants.
Best Practices
- Prefer iterators and range-based for loops over raw pointer arithmetic in modern C++ — cleaner and safe from arithmetic bugs.
- Use
ptrdiff_t(notint) for pointer differences to handle large arrays on 64-bit systems.