Dereferencing in C
Dereferencing is a fundamental concept in the C programming language that involves accessing the value stored at a memory location pointed to by a pointer.
What is a Pointer?
In C, a pointer is a variable that holds the memory address of another variable. Pointers are used to indirectly access and manipulate the values stored in memory.
Dereferencing a Pointer
To dereference a pointer, you use the unary * operator, also known as the dereference operator. When you dereference a pointer, you are essentially asking the compiler to retrieve the value stored at the memory address held by the pointer.
Example
#include <stdio.h>
int main() {
int x = 10; // Declare and initialize an integer variable
int* ptr = &x; // Declare a pointer and assign it the address of x
printf("Value of x: %d\n", x); // Output: 10
printf("Address of x: %p\n", (void*)&x); // Output: Memory address of x
printf("Value of ptr: %p\n", (void*)ptr); // Output: Same as above
printf("Dereferenced value of ptr: %d\n", *ptr); // Output: 10
// Modify the value of x through the pointer
*ptr = 20;
printf("Value of x after modification: %d\n", x); // Output: 20
return 0;
}
In this example:
- We declare an integer variable
x and initialize it to 10.
- We declare a pointer
ptr and assign it the address of x using the unary & operator.
- We print the value of
x, its address, and the value of ptr (which is the same as the address of x).
- We dereference
ptr using the unary * operator and print the resulting value, which is 10.
- We modify the value of
x by assigning a new value to the dereferenced ptr.
- We print the updated value of
x to verify that the modification was successful.
Key Takeaways
- Dereferencing a pointer involves using the unary
* operator to access the value stored at the memory address held by the pointer.
- Pointers are used to indirectly access and manipulate values in memory.
- Dereferencing a pointer allows you to read or modify the value stored at the pointed-to memory location.