Programming in C

(Barry) #1

240 Chapter 11 Pointers


int i1, i2;
int *p1, *p2;

i1 = 5;
p1 = &i1;
i2 = *p1 / 2 + 10;
p2 = p1;

printf ("i1 = %i, i2 = %i, *p1 = %i, *p2 = %i\n", i1, i2, *p1, *p2);

return 0;
}

Program 11.3 Output
i1 = 5, i2 = 12, *p1 = 5, *p2 = 5

After defining the integer variables i1and i2and the integer pointer variables p1and
p2, the program then assigns the value 5 to i1and stores a pointer to i1inside p1. Next,
the value of i2is calculated with the following expression:
i2 = *p1 / 2 + 10;
In As implied from the discussions of Program 11.2, if a pointer pxpoints to a variable x,
and pxhas been defined to be a pointer to the same data type as is x, then use of *pxin
an expression is, in all respects, identical to the use of xin the same expression.
Because in Program 11.3 the variable p1is defined to be an integer pointer, the pre-
ceding expression is evaluated using the rules of integer arithmetic. And because the value
of *p1is 5 (p1points to i1), the final result of the evaluation of the preceding expression
is 12 ,which is the value that is assigned to i2. (The pointer reference operator *has
higher precedence than the arithmetic operation of division. In fact, this operator, as well
as the address operator &, has higher precedence than allbinary operators in C.)
In the next statement, the value of the pointer p1is assigned to p2.This assignment is
perfectly valid and has the effect of setting p2to point to the same data item to which p1
points. Because p1points to i1, after the assignment statement has been executed,p2also
points to i1(and you can have as many pointers to the same item as you want in C).
The printfcall verifies that the values of i1,*p1,and *p2are all the same ( 5 ) and
that the value of i2was set to 12 by the program.

Working with Pointers and Structures


You have seen how a pointer can be defined to point to a basic data type, such as an int
or a char. But pointers can also be defined to point to structures. In Chapter 9,
“Working with Structures,” you defined your datestructure as follows:

Program 11.3 Continued
Free download pdf