Topic 39 of 83
Dereferencing
Overview
Dereferencing uses the `*` operator on a pointer to access or modify the actual value stored at the memory address it points to.
Syntax
cpp
int x = 10;
int* ptr = &x;
// Dereferencing to read value
cout << *ptr; // Prints 10
// Dereferencing to write value
*ptr = 20; // Modifies x to 20Common Pitfalls
- Dereferencing a pointer that hasn't been initialized (wild pointer). It will read or overwrite random memory, causing a crash.
Interview Tips
- Understand the dual use of the `*` symbol: in declarations (`int* p`), it means 'pointer to int'. In expressions (`*p = 5`), it means 'value at address'.
Real-World Example
Modifying variables indirectly via pointers.
example
cpp
#include <iostream>
using namespace std;
int main() {
int bankBalance = 500;
int* ptr = &bankBalance;
// Modify through pointer
*ptr += 100; // Deposits 100
cout << "Balance is now: " << bankBalance << endl; // Prints 600
return 0;
}