Dereferencing in C++ allows access to the actual value stored at a memory address, rather than just the address itself.
Getting a Variable’s Memory Address
Using the &
(address-of) operator, the memory location where a variable is stored can be retrieved.
Example: Displaying a Memory Address
C++
x
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 variable’s 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
C++
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:
C++
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.