Pointers and References
💻 C++Understand memory addresses, references and when a pointer is necessary.
A pointer holds an address. A reference is another name for an existing object. Both avoid copying, but they behave differently.
- Declare and dereference pointers.
- Use references.
- Avoid dangling pointers.
Pointers
& takes an address and * reads the value at that address. Always check a pointer before dereferencing it.
int score = 88;
int* pointer = &score;
std::cout << pointer << "\n"; // address
std::cout << *pointer << "\n"; // 88
*pointer = 92;
std::cout << score << "\n"; // 92References
A reference must be initialised and cannot be reseated. It is the safer default for passing values without copying.
int score = 88;
int& alias = score;
alias = 95;
std::cout << score << "\n"; // 95Lifetime
Never return a pointer or reference to a local variable. It is destroyed when the function ends, leaving a dangling pointer.
Practice
- Create a pointer to an int and print both the address and value.
- Change a value through a reference.
- Explain why returning a reference to a local variable is unsafe.
Hands-on exercise
Write a function swapValues(int& a, int& b) that swaps two numbers using references.
Call it and print the values before and after.
Recap
Pointers store addresses and can be null. References are aliases and cannot be reseated. Watch object lifetimes.
Example
int score = 88;
int* pointer = &score;
std::cout << pointer << "
"; // address
std::cout << *pointer << "
"; // 88
*pointer = 92;
std::cout << score << "
"; // 92
Exercises
Call it and print the values before and after.
Expected Output
3 7
7 3
Lesson Nav
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project