Pointers and Addresses
Store an address, dereference it, and modify the original object.
What is Pointers and Addresses?
A pointer contains the address of an object of a compatible type; dereferencing accesses the object at that address.
Important points
- Every pointer must refer to a live compatible object or be null.
- Pair each owned allocation with exactly one release.
- Prefer clear ownership and const-correct interfaces.
C and C++ code examples
#include <stdio.h>
int main(void) {
int score = 70;
int *score_ptr = &score;
*score_ptr += 5;
printf("score=%d same-address=%s\n", score,
score_ptr == &score ? "yes" : "no");
return 0;
}
score=75 same-address=yes
#include <iostream>
int main() {
int score = 70;
int* score_ptr = &score;
*score_ptr += 5;
std::cout << "score=" << score << " same-address="
<< std::boolalpha << (score_ptr == &score) << '\n';
}
score=75 same-address=true
C and C++ comparison
The C example uses a raw pointer directly. C++ still supports raw pointers for non-owning access; references are often preferred when null is not meaningful.
Ownership and cleanup are conventions enforced by the programmer.
Containers and RAII types can encode ownership and cleanup in object lifetimes.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Test null and allocation-failure paths.
- Run with AddressSanitizer and UndefinedBehaviorSanitizer.
- Document whether every pointer owns or only observes its object.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges