Pointers in C: Using Pointers in Expressions

In Program 11.3, two integer pointers, p1 and p2, are defined. Notice how the value referenced by a pointer can be used in an arithmetic expression. If p1 is defined to be of type “pointer to integer,” what conclusion do you think can be made about the use of *p1 in an expression?

Program 11.3   Using Pointers in Expressions

// More on pointers

#include <stdio.h>

int main (void)

{

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 i1 and i2 and the integer pointer variables p1 and p2, the program then assigns the value 5 to i1 and stores a pointer to i1 inside p1. Next, the value of i2 is calculated with the following expression:

i2 = *p1 / 2 + 10;

In As implied from the discussions of Program 11.2, if a pointer px points to a variable x, and px has been defined to be a pointer to the same data type as is x, then use of *px in an expression is, in all respects, identical to the use of x in the same expression.

Because in Program 11.3 the variable p1 is defined to be an integer pointer, the pre- ceding expression is evaluated using the rules of integer arithmetic. And because the value of *p1 is 5 (p1 points 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 all binary operators in C.)

In the next statement, the value of the pointer p1 is assigned to p2.This assignment is perfectly valid and has the effect of setting p2 to point to the same data item to which p1 points. Because p1 points to i1, after the assignment statement has been executed, p2 also points to i1 (and you can have as many pointers to the same item as you want in C).

The printf call verifies that the values of i1, *p1, and *p2 are all the same (5) and that the value of i2 was set to 12 by the program.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *