问题是这段代码不会互换这两个字符串。我是编程新手,但我可以说问题出在交换函数上,但我不知道如何修复它。
我尝试在交换中添加 strcpy 而不是“=”,但没有成功。
#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;
}
最佳答案
你想在这里使用 out 参数,因为你的字符串被表示为指针,你需要指向指针的指针:
void swap(char **t1, char **t2) {
char *t;
t = *t1;
*t1 = *t2;
*t2 = t;
}
这样调用它:
swap(&s[0], &s[1]);
I tried to add strcpy instead of "=" in swap but that didn't worked.
之所以不起作用,是因为字符串实际上存储在程序的二进制文件中,因此无法修改,而使用 strcpy
可以覆盖它们。如果您将它们复制到堆栈或堆中,那么您可以使用 strcpy
进行交换。当然,这会比仅仅交换指针效率低,但这就是它的样子:
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);
}
此外,您还需要将 s
的定义更改为类似于
char s[2][16] = { "Hello", "World" }; // strings are copied to the stack now
关于c - 我如何使字符串数组与交换函数交换它的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54534509/