The indirection operator is a unary operator represented by the symbol asterisk (*). It is an operator used to obtain the value of a variable to which a pointer points. While a pointer pointing to a variable provides an indirect access to the value of the variable stored in it's memory address, the indirection operator dereference the pointer and returns the value of the variable at the memory location.
Indirection Operator:
- '*' It is called indirection operator.
- '*' (asterisk symbol) is also know as dereferencing operator.
- '*' It is an unary operator.
- It takes address as an arguments.
- '*' returns the content whose address is its argument.
Let's understand how indirection operator is used for obtaining the value of a variable see at below example.
Indirection Operator | welcome2protec.com |
Example 1: Indirection operator
#include <stdio.h>
int main()
{
int var = 10;
printf("%d\n", var);
printf("%p\n", &var);
printf("%d\n", *&var);
}
- Format specifier %p is used for printing address in hexadecimal format.
- Address of operator (&) gives the address of variable.
- Indirection operator (*) used to access the value of variable to which a pointer points.
Output
10
0xbffd8b3c4c
10
Example 2: Indirection operator
#include <stdio.h>
int main()
{
int var = 10, *ptr;
ptr = &var;
printf("%d %p\n", var, ptr);
printf("%d %p\n", *ptr, &var);
printf("%p\n", *&ptr);
}
Output
10 0xbffd8b3c4c
10 0xbffd8b3c4c
0xbffd8b3c4c
How to access value of var using pointer?
To display the value of var using pointer, the unary operator * is used which returns the value of variable var whose address is stored by the pointer (i.e. *ptr). Let's have a look at the below example.
#include <stdio.h>
int main()
{
int var=10;
int *ptr;
ptr= &var
/* We are using *ptr to access the value stored at the memory location
* to whome ptr is currently pointing to. */
printf("Value of var is %d",*ptr);
/* To change the value of var simply write *ptr = 20 */
*ptr = 20
printf("Value of var is now been cahnged to %d",*ptr);
}
Output
Value of var is 10
Value of var is now been cahnged to 20
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.