Labs ICT
โญ Pro Login

Pointers

A pointer is a variable that holds a memory address. Instead of storing a value directly, it stores where that value lives in the computer's memory. This is one of the most powerful โ€” and most confusing โ€” concepts in C++.

Address-of and Dereference

The & operator gives you the address of a variable. The * operator (dereference) lets you access the value stored at that address:

#include <iostream>

int main() {
  int age = 25;
  int* ptr = &age;

  std::cout << "Value of age: " << age << "\n";
  std::cout << "Address of age: " << ptr << "\n";
  std::cout << "Value at address: " << *ptr << "\n";

  *ptr = 30;

  std::cout << "New value of age: " << age << "\n";
  return 0;
}

int* ptr declares a pointer to an integer. &age gives us the address of age. *ptr reads the value at that address. When we assign *ptr = 30, we are actually changing age itself.

Why Pointers Matter

Pointers let you share data across functions without copying it. Instead of passing a whole array or a large object, you pass a single address. They are also essential for dynamic memory allocation, data structures like linked lists, and interfacing with hardware.

#include <iostream>

void doubleValue(int* p) {
  *p = *p * 2;
}

int main() {
  int num = 21;
  doubleValue(&num);
  std::cout << "Doubled: " << num << "\n";
  return 0;
}

The function receives the address of num and modifies the original variable directly. Without pointers, the function would only modify a copy and the original would stay unchanged.

Null Pointers

A pointer that does not point to anything valid should be set to nullptr. Dereferencing a null pointer crashes your program:

#include <iostream>

int main() {
  int* ptr = nullptr;

  if (ptr != nullptr) {
    std::cout << *ptr << "\n";
  } else {
    std::cout << "Pointer is null, cannot dereference\n";
  }
  return 0;
}

Always check for nullptr before using a pointer. It is a simple habit that prevents countless crashes.

๐Ÿงช Quick Quiz

What operator gives you the address of a variable?