Introduction
Pointers are also variables, but instead of storing a value like normal variables, they store the address of some other variable. We know that the pointers hold memory addresses of some other variables. But how can we get the value or data which is stored in the variable? The solution is to dereference the pointer.
Dereferencing is a technique for accessing or manipulating data stored in a memory location pointed to by a pointer. We use the * symbol with the pointer variable when dereferencing the pointer variable.
Using dereferencing, we can get the value inside the variable.
Also see: C Static Function, And Tribonacci Series
Demonstration
Now that we have defined what is meant by dereferencing a pointer, it's time to see it practically using code.
- Step 1: declare a variable and assign it a value.
int var =100;
- Step 2: Declare a pointer variable that will point to the variable var which we created above.
int *p;
- Step 3: Store the address of variable var in the pointer variable ptr. This is known as referencing.
p= &var;
- Step 4: We can now manipulate the value in variable var by dereferencing the pointer variable p, as shown below.
*p= 200;
This will now change the value of var from 100 to 200.
The pointer points to the memory address of the variable var. When we write p=&var, we let the pointer know the address of var. Now the pointer is holding the address of var. When we write *p=200, the * symbol tells the pointer to change the value of the variable.
Code
#include <stdio.h>
int main()
{
// declare a variable var and assign it a value 100
int var = 100;
// declare a pointer variable.
int *p;
// store the address of var
p = &var;
// change the value of var using dereferencing
// *p=200 is equivalent to var=200
// here without using var we change the value of var using the pointer
*p = 200;
// print the changed value of var
printf("value of var is : %d", var);
return 0;
}
Output:
value of var is : 200
You can also read about the dynamic arrays in c and Short int in C Programming