Saturday, May 10, 2008

Pointer & functions

Pointer & functions

Let us now examine the close relationship between pointers
and C's other major parts. We will start with functions.

When C passes arguments to functions it passes them by value.

There are many cases when we may want to alter a passed
argument in the function and receive the new value back
once the function has finished.

C uses pointers explicitly to do this.

The best way to study this is to look at an example
where we must be able to receive changed parameters.
Let us try and write a function to swap variables around?

The usual function call:

swap (a, b) won't work.

Pointers provide the solution: Pass the address of the
variables to the functions and access address of function.

Thus our function call in our program would look like this:

swap (&a, &b)

The Code to swap is fairly straightforward:

void swap(int *px, int *py)
{ int temp;
temp = *px;
/* contents of pointer */
*px = *py;
*py = temp;
}

0 comments:

Copyright

Copyright © 2008 C Tutorial, All rights are reserved