Dereference Operator in C: What It Is and How It Works
* symbol is called the dereference operator. It is used to access or modify the value stored at the memory address held by a pointer variable.How It Works
The dereference operator * lets you reach inside a pointer to get or change the actual value it points to. Think of a pointer as a street address written on a piece of paper. The dereference operator is like going to that address and opening the door to see what's inside.
When you declare a pointer, it holds the memory address of a variable, not the variable's value itself. Using *pointer means you are asking: "Give me the value stored at this address." This is essential for working with dynamic data and for efficient memory use.
Example
This example shows how to declare a pointer, assign it the address of a variable, and then use the dereference operator to access and change the variable's value.
#include <stdio.h> int main() { int number = 10; int *ptr = &number; // ptr holds the address of number printf("Original value: %d\n", number); *ptr = 20; // change value at the address ptr points to printf("New value: %d\n", number); return 0; }
When to Use
Use the dereference operator when you want to work directly with the value stored at a memory address, especially when using pointers. This is common in:
- Modifying variables inside functions via pointers.
- Working with dynamic memory allocation.
- Accessing elements in data structures like linked lists or trees.
It helps write efficient programs by avoiding copying large amounts of data and enabling flexible data manipulation.
Key Points
- The dereference operator
*accesses the value at a pointer's address. - It is different from the address-of operator
&, which gets the address of a variable. - Using
*on a pointer lets you read or change the original variable. - Always ensure the pointer points to a valid memory location before dereferencing to avoid errors.