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

别来无恙 提交于 2020-01-04 04:43:07

问题


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;
}

回答1:


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



回答2:


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.




回答3:


You need to passing the pointer of pointer, i.e. address of the position in array where the strings are present, so that you can swap and place correct addresses there.

Try the below code:

#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;
}

Output:

World
Hello


来源:https://stackoverflow.com/questions/54534509/how-i-can-make-a-string-array-interchange-its-components-with-a-swap-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!