C++•Pointers & References
C++ Pointers and References: Memory Addresses Explained
Pointers hold memory addresses directly, enabling manual memory manipulation, while references provide safe aliases.
Syntax
int* ptr = &val;
int& ref = val;
*ptr = 20;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| & | Address-of Operator | Retrieves the memory address of a variable. |
| * | Dereference Operator | Accesses or mutates value stored at memory address. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
int main() {
int target = 42;
int* ptr = ⌖ // ptr stores memory address of target
int& ref = target; // ref is an alias for target
std::cout << "Original Value: " << target << "\n";
std::cout << "Memory Address: " << ptr << "\n";
std::cout << "Dereferenced Value: " << *ptr << "\n";
// Mutate via pointer dereference
*ptr = 100;
std::cout << "\nAfter *ptr = 100:\n";
std::cout << " target: " << target << "\n";
std::cout << " ref: " << ref << "\n";
return 0;
}Expected Output:
Original Value: 42 Memory Address: [address] Dereferenced Value: 42 After *ptr = 100: target: 100 ref: 100
How It Works: Step-by-Step
- Lines 5-6: Assigns address of target to pointer and binds reference alias.
- Line 10: *ptr dereferences address to read stored integer.
- Line 13: Writing to *ptr directly mutates target in memory.
Key Concepts
- Pointers can be reassigned to point elsewhere and can be nullptr.
- References cannot be null and cannot be reseated after initialization.
- Dereferencing a nullptr or uninitialized pointer causes Segmentation Fault.
Common Mistake: Dereferencing a nullptr or uninitialized pointer
Accessing memory at an invalid address crashes the program with a segmentation fault.
❌ Incorrect
int* ptr = nullptr; *ptr = 10; // Segmentation Fault (Crash)!
✅ Correct
int val = 0; int* ptr = &val; *ptr = 10; // Safe
Related C++ Tutorials & Compiler
C++ Functions: Pass-by-Value, Pass-by-Reference, and Const
Understand function parameters, pass-by-value vs pass-by-reference (&), and const correctness.
C++ Classes and Object-Oriented Programming (OOP)
Construct object blueprints with public/private access specifiers, constructors, and destructors.
C++ Smart Pointers and RAII Memory Management (C++11)
Master modern C++ memory management using std::unique_ptr, std::shared_ptr, and RAII.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.