Search code examples
cpointerspass-by-referenceswappass-by-value

Why doesn't this swapping function work? (swapping strings in C)


I am trying to swap 2 entries in an array of strings, but my swap function doesn't swap when called.

swap(char*, char*);

int main() {
    char *ptsr[2] = { "x", "y" };
    swap(ptsr[0], ptsr[1]);
}

swap(char *t1, char *t2) {
    char *t;
    t = t1;
    t1 = t2;
    t2 = t;
}

Can someone identify and explain my mistake?


Solution

  • C is strictly pass by value. You pass the values of ptsr[0] and pstr[1] to swap. It swaps where it keeps those two values, but that has no effect on the calling function. Consider:

    swap (int v1, int v2)
    {
        int t;
        t = v1;
        v1 = v2;
        v2 = t;
    }
    

    This is the same as your swap function, just using int instead. It should be pretty clear that if you call swap(1,2);, the swap function just puts the 2 where it was storing the 1 and vice versa, but that has no effect on anything in the caller.

    Same if you do this:

    int i = 2;
    int j = 3;
    swap(i,j);
    

    Since all you passed to swap is the values 2 and 3, it cannot affect the values of i and j by any means.

    And same with your swap function if you do this:

    char* j = "hello";
    char* k = "world";
    swap(j,k);
    

    The function receives "hello" and "world" and swaps where it stores those two pointers. This has no effect on j or k in the caller.

    C is strictly pass by value. Whatever parameters you pass to a function, the function only receives the values of.