Example 1: Dereference Operator

The dereference operator (*) in C++ is used to access the value stored at a memory address when working with pointers. A pointer holds the memory address of another variable, and the dereference operator allows us to retrieve or modify the value at that address.


Code Example

#include <iostream>

int main() {
    int num = 10;       // Declare an integer variable
    int* ptr = &num;    // Declare a pointer and store the address of num

    // Dereferencing the pointer to access the value
    std::cout << "Value of num: " << num << std::endl;
    std::cout << "Address of num: " << &num << std::endl;
    std::cout << "Pointer ptr stores address: " << ptr << std::endl;
    std::cout << "Value at address stored in ptr (*ptr): " << *ptr << std::endl;

    // Modifying value using the pointer
    *ptr = 20;
    std::cout << "Updated value of num after modifying through pointer: " << num << std::endl;

    return 0;
}

Explanation & Output

Code Breakdown:

  1. Declaring and Initializing a Pointer:
    • int num = 10; → Creates an integer variable num with value 10.
    • int* ptr = &num; → Creates a pointer ptr that stores the memory address of num.
  2. Dereferencing the Pointer (*ptr):
    • *ptr returns the value stored at the address ptr is pointing to, which is num.
  3. Modifying the Value through Pointer:
    • *ptr = 20; modifies num through the pointer, demonstrating how pointers allow indirect modification of variables.

Expected Output:

Value of num: 10
Address of num: 0x61ff08  // (Example memory address, varies per execution)
Pointer ptr stores address: 0x61ff08
Value at address stored in ptr (*ptr): 10
Updated value of num after modifying through pointer: 20

The exact memory addresses will vary during execution. However, the key takeaway is that the pointer stores the address of num, and dereferencing it (*ptr) allows both reading and modifying num’s value.