Prev NEXT

The Basics of C Programming

Using Pointers for Function Parameters

Most C programmers first use pointers to implement something called variable parameters in functions. You have actually been using variable parameters in the scanf function -- that's why you've had to use the & (the address operator) on variables used with scanf. Now that you understand pointers you can see what has really been going on.

To understand how variable parameters work, lets see how we might go about implementing a swap function in C. To implement a swap function, what you would like to do is pass in two variables and have the function swap their values. Here's one attempt at an implementation -- enter and execute the following code and see what happens:

Advertisement

#include <stdio.h>

void swap(int i, int j)
{
    int t;

    t=i;
    i=j;
    j=t;
}

void main()
{
    int a,b;

    a=5;
    b=10;
    printf("%d %d\n", a, b);
    swap(a,b);
    printf("%d %d\n", a, b);
}

When you execute this program, you will find that no swapping takes place. The values of a and b are passed to swap, and the swap function does swap them, but when the function returns nothing happens.

To make this function work correctly you can use pointers, as shown below:

#include <stdio.h>

void swap(int *i, int *j)
{
    int t;
    t = *i;
    *i = *j;
    *j = t;
}

void main()
{
    int a,b;
    a=5;
    b=10;
    printf("%d %d\n",a,b);
    swap(&a,&b);
    printf("%d %d\n",a,b);
}

To get an idea of what this code does, print it out, draw the two integers a and b, and enter 5 and 10 in them. Now draw the two pointers i and j, along with the integer t. When swap is called, it is passed the addresses of a and b. Thus, i points to a (draw an arrow from i to a) and j points to b (draw another arrow from b to j). Once the pointers are initialized by the function call, *i is another name for a, and *j is another name for b. Now run the code in swap. When the code uses *i and *j, it really means a and b. When the function completes, a and b have been swapped.

Suppose you accidentally forget the & when the swap function is called, and that the swap line accidentally looks like this: swap(a, b);. This causes a segmentation fault. When you leave out the &, the value of a is passed instead of its address. Therefore, i points to an invalid location in memory and the system crashes when *i is used.

This is also why scanf crashes if you forget the & on variables passed to it. The scanf function is using pointers to put the value it reads back into the variable you have passed. Without the &, scanf is passed a bad address and crashes.

Variable parameters are one of the most common uses of pointers in C. Now you understand what's happening!