Question:

What is indirection?

Answer:

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 pis a pointer to a constant, *p is not a modifiable lvalue; it can't go on the left side of an assignment.

Consider the following program. It shows that when p points to i*p can appear wherever i can.

#include <stdio.h>
int main()
{
        int i;
        int *p;
        i = 5;
        p = & i;    /* now *p == i */
        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;
}

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.


Keywords:

© 2017 QuizBucket.org