C++ Pointers
A pointer is a variable which keeps the memory address of another variable. This is the most important and most difficult idea of C++.
Address and dereference
#include <iostream>
int main() {
int n = 42;
int* p = &n; // & gives the address of n
std::cout << *p << '\n'; // * follows the pointer to the value
*p = 99; // change n through the pointer
std::cout << n << '\n';
std::cout << std::boolalpha << (p == &n) << '\n';
}
Output
42
99
true
nullptr
A pointer which points to nothing should be nullptr (not 0 or NULL). Always check before you use it.
#include <iostream>
int main() {
int* p = nullptr;
if (p == nullptr) {
std::cout << "p points to nothing\n";
}
if (!p) {
std::cout << "same check, shorter\n";
}
}
Output
p points to nothing
same check, shorter
Pointers and arrays
#include <iostream>
int main() {
int a[4] = {10, 20, 30, 40};
int* p = a; // the name of the array is the address of its first item
std::cout << *p << ' ' << *(p + 1) << ' ' << p[2] << '\n';
p++; // move to the next int
std::cout << *p << '\n';
std::cout << (a + 3) - a << '\n'; // distance in items
}
Output
10 20 30
20
3
const and pointers
| Declaration | Meaning |
|---|---|
| const int* p | Pointer to a const int: you can not change the value through p |
| int* const p | A const pointer: p can not point to another place |
| const int* const p | Both are const |
int main() {
int a = 1, b = 2;
const int* p = &a;
*p = 5; // error: the value is const through this pointer
}
Output
Const.cpp: In function 'int main()':
Const.cpp:4:8: error: assignment of read-only location '* p'
4 | *p = 5; // error: the value is const through this pointer
| ~~~^~~
Const.cpp:2:16: warning: unused variable 'b' [-Wunused-variable]
2 | int a = 1, b = 2;
| ^
Pointer to a struct or object: the arrow
#include <iostream>
#include <string>
struct Student {
std::string name;
int marks;
};
int main() {
Student s{"Riya", 88};
Student* p = &s;
std::cout << p->name << ' ' << (*p).marks << '\n';
}
Output
Riya 88
Common mistakes
- Using a pointer which was never set (a wild pointer).
- Using a pointer after the memory was freed (a dangling pointer).
- Dereferencing
nullptr: the program crashes. - Going outside an array with pointer arithmetic.
Note:
In modern C++ prefer references, containers and smart pointers. Use raw pointers mostly to look at things, not to own them. Next: C++ Dynamic Memory and Smart Pointers.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |