Total Pageviews

Saturday 5 May 2012

Pointer and Functions


Pointer and 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 to function has finished. Other languages do this (e.g. var parameters in PASCAL). C uses pointers explicitly to do this. Other languages mask the fact that pointers also underpin the implementation of 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;
                   }

We can return pointer from functions. A common example is when passing back structures. e.g.:

typedef struct {float x,y,z;} COORD;
        main()
         {  COORD p1, *coord_fn();  /* declare fn to                           
                                      return ptr of COORD type */
            ....
          
            p1 = *coord_fn(...);    /* assign contents of
                                        address returned */
            ....
         }

   COORD *coord_fn(...)

                {  COORD p;
                   .....
                   p = ....;    /* assign structure values */
                   return &p;   /* return address of p */
                }

Here we return a pointer whose contents are immediately unwrapped into a variable. We must do this straight away as the variable we pointed to was local to a function that has now finished. This means that the address space is free and can be overwritten. It will not have been overwritten straight after the function ha squit though so this is perfectly safe.

No comments:

Post a Comment