HexLab

Lesson 6

Pointers and References

Understanding pointers and references for memory management in C++.

Lesson content

Pointers and References

Pointers and references are fundamental to C++ programming. A pointer is a variable that stores a memory address, while a reference is an alias to an existing variable.

Pointers

A pointer is declared using the * symbol and stores the memory address of another variable.

  • & (address-of operator) gets the address of a variable
  • * (dereference operator) accesses the value at a pointer address
  • -> (arrow operator) accesses members through a pointer

References

A reference is an alias to an existing variable. References cannot be null and must be initialized when declared.

Pointer Example

int x = 10;
int* ptr = &x;      // ptr stores address of x
cout << *ptr << endl; // outputs 10
cout << ptr << endl;  // outputs memory address