CITS2002 Systems Programming  
next CITS2002 CITS2002 schedule  

Passing pointers to functions

Consider a very simple function, whose role is to swap two integer values:

#include <stdio.h>

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

    temp = i;
    i    = j;
    j    = temp;
}

int main(int argc, char *argv[])
{
    int a=3, b=5;  // MULTIPLE DEFINITIONS AND INITIALIZATIONS  

    printf("before a=%i, b=%i\n", a, b);

    swap(a, b);    // ATTEMPT TO SWAP THE 2 INTEGERS

    printf("after  a=%i, b=%i\n", a, b);
    return 0;
}

before a=3, b=5
after  a=3, b=5

Doh! What went wrong?

The "problem" occurs because we are not actually swapping the values contained in our variables a and b, but are (successfully) swapping copies of those values.

 


CITS2002 Systems Programming, Lecture 12, p1, 28th August 2024.