Programming in C

(Barry) #1
Using Pointers in Expressions 239

(and notby the statements


char char_pointer;
char_pointer = &c;


as might be implied from the single-line declaration).
Always remember, that the value of a pointer in C is meaningless until it is set point-
ing to something.
The first printfcall simply displays the contents of the variable cand the contents of
the variable that is referenced by char_pointer. Because you set char_pointerto point
to the variable c, the value that is displayed is the contents of c, as verified by the first
line of the program’s output.
In the next line of the program, the character '/'is assigned to the character variable
c. Because char_pointerstill points to the variable c, displaying the value of
char_pointerin the subsequent printfcall correctly displays this new value of cat
the terminal.This is an important concept. Unless the value of char_pointeris
changed, the expression
char_pointeralwaysaccesses the value of c.So, as the value of
cchanges, so does the value of char_pointer.
The previous discussion can help you to understand how the program statement that
appears next in the program works. Unless char_pointeris changed, the expression
char_pointeralways references the value of c.Therefore, in the expression


*char_pointer = '(';


you are assigning the left parenthesis character to c. More formally, the character '('is
assigned to the variable that is pointed to by char_pointer.You know that this variable
is cbecause you placed a pointer to cin char_pointerat the beginning of the pro-
gram.
The preceding concepts are the key to your understanding of the operation of point-
ers. Please review them at this point if they still seem a bit unclear.


Using Pointers in Expressions


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


Program 11.3 Using Pointers in Expressions


// More on pointers


#include <stdio.h>


int main (void)
{

Free download pdf