[prev] [index] [next]

Pointers (cont)

  • swap() – the right way

    void swap(int *p, int *q) {
        int temp;
        temp = *p; *p = *q; *q = temp;   // will change the actual values of a and b
    }
    
    void test(void) {
        int a = 5, b = 7;
        swap(&a, &b);
        printf("a = %d, b = %d\n", a, b);  // a and b will now be successfully swapped
    }