Programming in C

(Barry) #1

238 Chapter 11 Pointers


Program 11.2 illustrates some interesting properties of pointer variables. Here, a
pointer to a character is used.

Program 11.2 More Pointer Basics
// Further examples of pointers

#include <stdio.h>

int main (void)
{
char c = 'Q';
char *char_pointer = &c;

printf ("%c %c\n", c, *char_pointer);

c = '/';
printf ("%c %c\n", c, *char_pointer);

*char_pointer = '(';
printf ("%c %c\n", c, *char_pointer);

return 0;
}

Program 11.2 Output
Q Q
/ /
( (

The character variable cis defined and initialized to the character 'Q'. In the next line
of the program, the variable char_pointeris defined to be of type “pointer to char,”
meaning that whatever value is stored inside this variable should be treated as an indirect
reference (pointer) to a character. Notice that you can assign an initial value to this vari-
able in the normal fashion.The value that you assign to char_pointerin the program is
a pointer to the variable c, which is obtained by applying the address operator to the
variable c. (Note that this initialization generates a compiler error if chad been defined
afterthis statement because a variable must always be declared beforeits value can be ref-
erenced in an expression.)
The declaration of the variable char_pointerand the assignment of its initial value
could have been equivalently expressed in two separate statements as
char *char_pointer;
char_pointer = &c;
Free download pdf