Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 424
Andrew Avatar asked Mar 06 '26 07:03

Andrew


2 Answers

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
like image 98
Blaze Avatar answered Mar 07 '26 19:03

Blaze


Check the types carefully.

What you have got as array members are pointers (to the starting element of string literals). You need to swap the members in a way so that they point to the other string literal. So, you need to change those pointers themselves.

So, you need to pass pointer to those pointers and then make the change from the called function.

Do something like

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

and then, in the called function:

void ptrSwap(char **t1, char **t2) {
    char *temp;
    temp=*t1;
    *t1=*t2;
    *t2=temp;
}

Bonus points: Name your functions (and variables, too, wherever applicable) meaningfully.

like image 41
Sourav Ghosh Avatar answered Mar 07 '26 20:03

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!