Programming in C

(Barry) #1
Defining a Pointer Variable 237

Program 11.1 Illustrating Pointers


// Program to illustrate pointers


#include <stdio.h>


int main (void)
{
int count = 10, x;
int *int_pointer;


int_pointer = &count;
x = *int_pointer;

printf ("count = %i, x = %i\n", count, x);

return 0;
}


Program 11.1 Output


count = 10, x = 10


The variables countand xare declared to be integer variables in the normal fashion. On
the next line, the variable int_pointeris declared to be of type “pointer to int.” Note
that the two lines of declarations could have been combined into the single line


int count = 10, x, *int_pointer;


Next, the address operator is applied to the variable count.This has the effect of creating
a pointer to this variable, which is then assigned by the program to the variable
int_pointer.
Execution of the next statement in the program,


x = *int_pointer;


proceeds as follows:The indirection operator tells the C system to treat the variable
int_pointeras containing a pointer to another data item.This pointer is then used to
access the desired data item, whose type is specified by the declaration of the pointer
variable. Because you told the compiler that int_pointerpoints to integers when you
declared the variable, the compiler knows that the value referenced by the expression
*int_pointeris an integer. And because you set int_pointerto point to the integer
variable countin the previous program statement, it is the value of countthat is indi-
rectly accessed by this expression.
You should realize that Program 11.1 is a manufactured example of the use of point-
ers and does not show a practical use for them in a program. Such motivation is present-
ed shortly, after you have become familiar with the basic ways in which pointers can be
defined and manipulated in a program.

Free download pdf