C++ Dereferencing

Dereferencing in C++ allows access to the actual value stored at a memory address, rather than just the address itself.

Tutorials dojo strip



Getting a Variable’s Memory Address

Using the & (address-of) operator, you can retrieve the memory location where a variable is stored.

Example: Displaying a Memory Address

#include <iostream>
using namespace std;

int main() {
    string motorcycleBrand = "Harley-Davidson";  
    string* ptr = &motorcycleBrand;  

    // Output the memory address of motorcycleBrand
    cout << ptr << "\n";  

    return 0;
}

Instead of printing the value, this displays the memory location (e.g., 0x6dfed4).




Dereferencing a Pointer (* Operator)

The * (dereference operator) retrieves the actual value stored at a memory address.

Example: Accessing a Variable Through a Pointer

#include <iostream>
using namespace std;

int main() {
    string motorcycleBrand = "Harley-Davidson";  
    string* ptr = &motorcycleBrand;  

    // Reference: Outputs the memory address
    cout << ptr << "\n";  

    // Dereference: Outputs the actual value
    cout << *ptr << "\n";  

    return 0;
}

Output:

0x6dfed4  
Harley-Davidson  




Understanding the * Symbol

  • In declaration (string* ptr) → Creates a pointer variable.
  • Outside of declaration (*ptr) → Dereferences the pointer to get the stored value.
Tutorials dojo strip
Scroll to Top