[prev] [index] [next]

Pointers (cont)

For a function to be able to change the "actual" value of a variable, we need to pass a pointer as a parameter.
  • swap() – the wrong way

    void swap(int a, int b) {
        int temp;
        temp = a; a = b; b = temp;   // only the local "copies" of a and b will swap
    }
    
    void test(void) {
        int a = 5, b = 7;
        swap(a, b);
        printf("a = %d, b = %d\n", a, b);  // a and b will have their original value
    }