Pointers, References & Memory

⚡ C++ Lesson 8 Intermediate

C++ provides two ways to reference memory locations directly: Pointers and References. Understanding their differences is crucial for effective memory management.

1 Pointers vs. References

Pointers and references allow you to access values by their memory addresses:

  • Pointer (`Type*`): A variable storing a memory address. Can point to different addresses over time and can be set to `nullptr`. Must be dereferenced using `*` to access values.
  • Reference (`Type&`): An alias for an existing variable. Must be initialized when declared and cannot be reassigned to alias a different variable. Syntactically acts like a standard variable, requiring no dereferencing.
2 Pointers and References Code

Let's run a program illustrating pointers, references, and modifying variables in memory:

C++ — Pointers and References ▶ Run Code
#include <iostream>

int main() {
    int num = 42;

    // 1. Pointer declaration and dereference
    int *ptr = # 
    std::cout << "Address: " << ptr << ", Value via Pointer: " << *ptr << "\n";
    *ptr = 99; // Modify value via pointer

    // 2. Reference declaration (Alias)
    int &ref = num;
    std::cout << "Value via Reference: " << ref << "\n";
    ref = 150; // Modify value via reference (changes original num)

    std::cout << "Original num after modifications: " << num << "\n";

    return 0;
}
3 Code Challenge
Challenge: Write a program that declares a float variable and both a pointer and reference to it. Modify the float's value using the pointer first, and then the reference, printing the variable after each change to verify the modifications in memory.