Show 25 50 100
PDF
3 result(s) in C++ with 2+ ★ Clear

Index

Showing 3 topics
  1. Pointers
  2. Call by Value vs Call by Reference
  3. STL: vector, map, set
1 Index

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

p holds the address of x, so *p gives the value of x

C++ 8 lines
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++ 3 lines
int arr[] = {10, 20, 30};
int *p = arr;           // array name = address of first element
cout << *(p + 1);       // 20  (pointer arithmetic)

Q & A

  1. What is a null pointer?
    A pointer that points to nothing (nullptr). Dereferencing it crashes the program, so check before use.
  2. 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.
  3. What is a void pointer?
    A generic pointer (void*) that can hold the address of any type, but must be cast before dereferencing.
2 Index

Call by value passes a copy, so changes inside the function do not affect the caller. Call by reference passes the variable itself.

C++ 11 lines
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 Index

The Standard Template Library gives ready-made containers and algorithms.

vector (dynamic array) C++ 5 lines
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++ 6 lines
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++ 3 lines
set<int> s = {5, 1, 5, 3};  // unique and sorted: 1 3 5
s.insert(2);
cout << s.count(5);         // 1 = present
ContainerLookupNotes
vectorO(1) by indexContiguous, push_back amortised O(1)
map / setO(log n)Red-black tree, keeps keys sorted
unordered_map / setO(1) averageHash table, no order
stack / queuetop/front O(1)Adapters for LIFO / FIFO
priority_queuetop O(1), push O(log n)Max-heap by default