DevAcademia lesson/C++ Basics
Modify Pointers
Topic progressTopic 64 of 109 - 59% complete
~9 min lesson23 learning blocks3 code examples1 checks/interactions
Lesson outline
Pointer Modification Basics
Pointers can be modified in several ways:
- Changing the address they store
- Using pointer arithmetic (within the same array object)
- Applying type casting (with strict rules)
- Leveraging their close relationship with arrays (array-to-pointer decay)
Pointer Arithmetic
Pointer arithmetic automatically accounts for the size of the pointed-to type. For example, incrementing an int* advances by sizeof(int).
The result of subtracting two pointers to the same array is of type ptrdiff_t (a signed integer type).
Pointer Modification Examples
Advanced Pointer Operations
Pointer to Pointer: Allows multiple levels of indirection
Function Pointers: Store the address of functions
Smart Pointers: Modern C++ resource management (unique_ptr, shared_ptr, weak_ptr)
Pointer Safety: Guidelines to prevent errors such as memory leaks and dangling pointers
Pointer Safety Checklist
- Initialize pointers; prefer nullptr over 0/NULL.
- Only do arithmetic within a single array (or one-past-the-end). Never dereference one-past.
- Do not compare or subtract pointers from different objects.
- After delete, do not reuse the pointer (consider setting it to nullptr).
- Prefer smart pointers and standard containers to manage lifetime automatically.
Was this topic clear?