C++ Dereference Operator

πŸ‘‰ C++ Dereference Operator (*)

In C++, the dereference operator (*) is used to access or modify the value stored at the memory address held by a pointer.


πŸ”Ή 1. What Does Dereferencing Mean?

  • A pointer stores an address

  • Dereferencing means getting the value at that address


πŸ”Ή 2. Basic Dereference Example

int x = 10;
int *p = &x;

cout << p; // prints address of x
cout << *p; // prints value of x (10)


πŸ”Ή 3. Dereference to Modify Value

int x = 5;
int *p = &x;

*p = 20;

cout << x; // Output: 20

➑ Value changed using dereference.


πŸ”Ή 4. Dereference in Functions

void update(int *n) {
*n = 100;
}

int x = 10;
update(&x);

cout << x; // 100


πŸ”Ή 5. Dereference with Arrays

int arr[] = {10, 20, 30};
int *p = arr;

cout << *p; // 10
cout << *(p + 1); // 20
cout << *(p + 2); // 30


πŸ”Ή 6. Dereference a Pointer to Pointer

int x = 10;
int *p = &x;
int **pp = &p;

cout << **pp; // 10


πŸ”Ή 7. Dereference vs Declaration (* Meaning)

int *p; // * β†’ pointer declaration
*p = 10; // * β†’ dereference

πŸ‘‰ Same symbol, different meanings based on context.


πŸ”Ή 8. Dereference with const

Pointer to Constant

const int x = 10;
const int *p = &x;

// *p = 20; ❌ not allowed

Constant Pointer

int x = 10;
int *const p = &x;

*p = 20; // allowed


❌ Common Mistakes

❌ Dereferencing Uninitialized Pointer

int *p;
cout << *p; // undefined behavior

βœ” Correct

int x = 10;
int *p = &x;

❌ Dereferencing Null Pointer

int *p = nullptr;
cout << *p; // crash

πŸ” Dereference vs Address-of

Operator Meaning
&x Address of x
*p Value at address p

πŸ“Œ Summary

  • Dereference operator * accesses value at address

  • Used with pointers and pointer-to-pointer

  • Can read or modify data

  • Must never dereference NULL or uninitialized pointers

You may also like...