Pointers and Addresses
A pointer contains the address of an object of a compatible type; dereferencing accesses the object at that address.
What is Pointers and Addresses?
A pointer contains the address of an object of a compatible type; dereferencing accesses the object at that address.
Store an address, dereference it, and modify the original object.
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
main.c
#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
C++
main.cpp
#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.
C
Ownership and cleanup are conventions enforced by the programmer.
C++
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.