Search code examples
cswappass-by-valuefunction-call

How I can make a string array interchange it's components with a swap function?


The problem is that this code won't interchange these 2 strings. I'm new to programming but I can tell that the problem is that swap function, but I do not know how to fix it.

I tried to add strcpy instead of "=" in swap but that didn't worked.

#include <stdio.h>
#include <stdlib.h>

void swap(char *t1, char *t2) {
    char *t;
    t=t1;
    t1=t2;
    t2=t;
}
int main() {
    char *s[2] = {"Hello", "World"};
    swap(s[0], s[1]);
    printf("%s\n%s", s[0], s[1]);
    return 0;
}

Solution

  • You want to use out parameters here, and since your strings are represented as pointers, you need pointers to pointers:

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

    Call it like this:

    swap(&s[0], &s[1]);
    

    I tried to add strcpy instead of "=" in swap but that didn't worked.

    The reason why that doesn't work is because the strings are actually stored in the program's binary and therefore can't be modified, and with strcpy you would write over them. If you copy them to the stack or the heap instead then you can do the swap with strcpy. Of course that's going to be less efficient than just swapping the pointers, but this is how it would look like:

    void swap(char *t1, char *t2) {
        char buf[16]; // needs to be big enough to fit the string
        strcpy(buf, t1);
        strcpy(t1, t2);
        strcpy(t2, buf);
    }
    

    Also you would need to change the definition of s to something akin to

    char s[2][16] = { "Hello", "World" }; // strings are copied to the stack now