What is a pointer?
- C++ course
- Beginner
- Lesson 77/116
- 5 min
Learn that a pointer holds a memory address and is accessed with *.
What is a pointer?
A pointer is a variable that holds a memory address. It stores not an int itself, but its memory address. The syntax: int* p;. Here * says p is a pointer to int.
A pointer shows which variable it points to, so you can access that variable indirectly. Pointers are a powerful but delicate tool in C++; they let you manage memory directly, but mistakes cause undefined behavior. Unlike references, they can be null and can be re-bound.
Pointer versus reference
Pointers and references are similar but different. A reference is bound once and cannot be null; a pointer can be re-bound and can be nullptr. The syntax also differs: with a pointer you access the value via *p.
Pointers are used for dynamic memory, walking arrays, and expressing 'maybe empty' states. References are preferred when you need 'an alias for a variable that surely exists'. Both are useful in their own domain; which one to pick depends on the problem.
Practice Access a value through a pointer
Declare int x = 42;. Bind p to x's address with int* p = &x;. Print the value p points to using *p with std::cout.
Starter code
#include <iostream>
int main() {
// Declare x
// Bind p as a pointer to x
// Print the value
return 0;
}Sample solution
#include <iostream>
int main() {
int x = 42;
int* p = &x;
std::cout << *p << "\n";
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a pointer?
- A kind of array
- A variable that holds a memory address Correct answer
- A memory block
- A kind of reference
Explanation: A pointer is a variable that holds a memory address.
2 Pointer declaration
int x = 42;
int____ p = &x;
int x = 42;
int* p = &x;
Explanation: int* p = &x; makes p a pointer to x.
3 Match each expression to its meaning
| Term | Meaning |
|---|---|
int* p |
Pointer declaration |
&x |
Take address |
*p |
Access value |
42 |
Value |