Module 11: PointersIntermediate50 min read
Pointers, Memory Addresses, nullptr, Pointer Arithmetic & Const Pointers
Deep dive into memory addresses, & and * operators, nullptr, pointer arithmetic, pointer-to-pointer, void*, const pointers, and avoiding dangling/wild pointers.
Key Takeaways & Core Concepts
- `nullptr` (C++11): Type-safe null pointer literal (
std::nullptr_t), eliminatingNULL(0) overload ambiguity. - Wild Pointer: Uninitialized pointer -> initialize to
nullptr. - Dangling Pointer: Points to freed/out-of-scope memory -> set to
nullptrafterdelete.
1. Memory Addresses, `&`, `*`, and `nullptr`
A pointer holds the virtual memory address of an object.
&x: Address-of operator.*p: Dereference operator (reads/writes the value at addressp).- `nullptr` (C++11): Type-safe null pointer literal (
std::nullptr_t), eliminatingNULL(0) overload ambiguity.
1. Pointer Arithmetic, Double Pointer & Constness
1#include <iostream>
2
3int main() {
4 int vals[] = {10, 20, 30};
5 int* p = vals;
6 int** pp = &p;
7 std::cout << "First: " << **pp << ", Second: " << *(p + 1) << "\n";
8
9 const int x = 42;
10 const int* cp = &x;
11 std::cout << "Const target: " << *cp << "\n";
12 return 0;
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: Demonstrates pointer-to-pointer `**pp`, pointer arithmetic `*(p + 1)`, and `const int*`.
2. Pointer Arithmetic & Constness (Read Right-to-Left)
p + 1advances the address bysizeof(*p)bytes.const int* p: Pointer to constantint(cannot modify*p).int* const p: Constant pointer toint(cannot reseatp).const int* const p: Constant pointer to constantint.
3. Wild, Dangling & Void Pointers
- Wild Pointer: Uninitialized pointer -> initialize to
nullptr. - Dangling Pointer: Points to freed/out-of-scope memory -> set to
nullptrafterdelete. - `void
**: Typeless raw address; must bestatic_cast` before dereferencing.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)