Search This Blog

Translate

indirection operator in C

indirection operator in c example,indirection operator c language,use of indirection operator in c,purpose of indirection operator in c,indirection requires pointer operand,double dereference,c pointer to a pointer,c dereference,

What is indirection operator? Give an example.
The address of operator & is used to evaluate the address of its operand.
The indirection operator * is used to evaluate the value stored at the address given by its operand. The operand must be of pointer type; ie, it can either be an array (which is a self-referential pointer), a pointer to a variable (data pointer) or a pointer to a function (function pointer).
Example of a data pointer:
#include<stdio.h>
int main()
{
int val, a=10;
int *p;                       //declares a pointer variable
p=&a;                      //now p stores the address of a
val=*p;                  //now val stores the value of a
printf(" Address of a: %X", p);
printf("Value of a: %d",val);
return 0;
}
In the above program the statement int *p declares an integer pointer (a pointer that stores the address of an integer variable).
To store the address of a in p, the address of operator is applied to  a and the result is stored in p as shown in the instruction p=&a;
Now p=&a;
Suppose the address of a is 1004 i.e . &a=1004
Since  p stores  the address of a, then p=&a p=1004
Now the value present at the address 1004 is the value stored in a which is 10(a=10).
To access the value stored in a using the pointer variable p we need to apply the indirection operator * on p. When the indirection operator is applied on p (*p), it reads the value stored at the address contained in p; ie, the value stored at the address 1004; ie, the value of a. The result of indirection is stored in the integer type variable val  as shown in the statement val =*p;. The indirection operator is also called the value at operator as it gives the value stored at a particular address.
To read the address stored in p, the format specifier %X is used in the printf statement as addresses are generally in hexadecimal.
The relationship between pointers and arrays has been discussed to some extent while discussing the array subscript operator. Function pointers is an advanced concept that will be discussed in a later article on pointers.
The next article will continue with the unary operators and the other operators in C.


indirection operator in c example,indirection operator c language,use of indirection operator in c,purpose of indirection operator in c,indirection requires pointer operand,double dereference,c pointer to a pointer,c dereference,



C Program example List

Google+ Badge