Programming in C

(Barry) #1

254 Chapter 11 Pointers


Pointers and Functions


Pointers and functions get along quite well together.That is, you can pass a pointer as an
argument to a function in the normal fashion, and you can also have a function return a
pointer as its result.
The first case cited previously, passing pointer arguments, is straightforward enough:
The pointer is simply included in the list of arguments to the function in the normal
fashion. So, to pass the pointer list_pointerfrom the previous program to a function
called print_list,you can write
print_list (list_pointer);
Inside the print_listroutine, the formal parameter must be declared to be a pointer to
the appropriate type:
void print_list (struct entry *pointer)
{
...
}
The formal parameter pointercan then be used in the same way as a normal pointer
variable. One thing worth remembering when dealing with pointers that are sent to
functions as arguments:The value of the pointer is copied into the formal parameter
when the function is called.Therefore, any change made to the formal parameter by the
function does notaffect the pointer that was passed to the function. But here’s the catch:
Although the pointer cannot be changed by the function, the data elements that the
pointer references canbe changed! Program 11.8 helps clarify this point.

Program 11.8 Using Pointers and Functions
// Program to illustrate using pointers and functions

#include <stdio.h>

void test (int *int_pointer)
{
*int_pointer = 100;
}

int main (void)
{
void test (int *int_pointer);
int i = 50, *p = &i;

printf ("Before the call to test i = %i\n", i);
Free download pdf