C++
A pointer stores the memory address of another variable. & gives an address, * reads the value at an address (dereference).

p holds the address of x, so *p gives the value of x
C++
int x = 10;
int *p = &x; // p stores the address of x
cout << p; // address, e.g. 0x7ffe10
cout << *p; // 10
*p = 20; // changes x through the pointer
cout << x; // 20
int *q = nullptr; // points nowhere (always initialise pointers)
Pointer and array · C++
int arr[] = {10, 20, 30};
int *p = arr; // array name = address of first element
cout << *(p + 1); // 20 (pointer arithmetic)
Q & A
- What is a null pointer?
A pointer that points to nothing (nullptr). Dereferencing it crashes the program, so check before use.
- What is a dangling pointer?
A pointer that still holds the address of memory that has already been freed or has gone out of scope.
- What is a void pointer?
A generic pointer (void*) that can hold the address of any type, but must be cast before dereferencing.
2
Call by Value vs Call by Reference
★★★★★
↑ Index
C++
Call by value passes a copy, so changes inside the function do not affect the caller. Call by reference passes the variable itself.
C++
void byValue(int a) { a = 100; }
void byReference(int &a) { a = 100; }
void byPointer(int *a) { *a = 100; }
int main() {
int x = 1;
byValue(x); cout << x; // 1 (copy changed)
byReference(x); cout << x; // 100
x = 1;
byPointer(&x); cout << x; // 100
}
Tip: pass large objects as const T& to avoid copying and to stop accidental changes.
3
STL: vector, map, set
★★★★★
↑ Index
C++
The Standard Template Library gives ready-made containers and algorithms.
vector (dynamic array) · C++
vector<int> v = {3, 1, 2};
v.push_back(4); // add at end
sort(v.begin(), v.end()); // 1 2 3 4
cout << v.size(); // 4
for (int x : v) cout << x << " ";
map (key → value) · C++
map<string, int> age; // sorted by key
age["Rahim"] = 25;
age["Karim"] = 30;
for (auto &[name, a] : age)
cout << name << " " << a << endl;
if (age.count("Rahim")) cout << "found";
set (unique, sorted) · C++
set<int> s = {5, 1, 5, 3}; // unique and sorted: 1 3 5
s.insert(2);
cout << s.count(5); // 1 = present
| Container | Lookup | Notes |
|---|
| vector | O(1) by index | Contiguous, push_back amortised O(1) |
| map / set | O(log n) | Red-black tree, keeps keys sorted |
| unordered_map / set | O(1) average | Hash table, no order |
| stack / queue | top/front O(1) | Adapters for LIFO / FIFO |
| priority_queue | top O(1), push O(log n) | Max-heap by default |