Monday 7 November 2011

What is indirection? in C programming

What is indirection?

If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any
other object in memory, you have an indirect reference to its value. If p is a pointer, the value of p is the address
of the object. *p means “apply the indirection operator to p”; its value is the value of the object that p points
to. (Some people would read it as “Go indirect on p.”)

*p is an lvalue; like a variable, it can go on the left side of an assignment operator, to change the value. If p
is a pointer to a constant, *p is not a modifiable lvalue; it can’t go on the left side of an assignment. (See FAQ
II.4 and the discussion at the beginning of this chapter.) Consider the following program. It shows that when
p points to i, *p can appear wherever i can

An example of indirection.

#include <stdio.h>
int
main()
{
int i;
int *p;
i = 5;
p = & i; /* now *p == i */
/* %P is described in FAQ VII.28 */
printf(“i=%d, p=%P, *p=%d\n”, i, p, *p);
*p = 6; /* same as i = 6 */
printf(“i=%d, p=%P, *p=%d\n”, i, p, *p);
return 0; /* see FAQ XVI.4 */
}
After p points to i (p = &i), you can print i or *p and get the same thing. You can even assign to *p, and
the result is the same as if you had assigned to i.

Cross Reference:

II.4: What is a const pointer?

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. 1. An indirection operator in C is also called dereferencing or value at operator in C.
    2. It is used to access or manipulate the data at a specific location i.e. any operation performed at the de-referenced pointer directly impact/changes the value at the particular location where the pointer is pointing.

    Credit Indirection in C

    ReplyDelete