c - 我如何使字符串数组与交换函数交换它的组件?

标签 c swap pass-by-value function-call

问题是这段代码不会互换这两个字符串。我是编程新手,但我可以说问题出在交换函数上,但我不知道如何修复它。

我尝试在交换中添加 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/

相关文章:

c - Windows 8.1 上带有 Cygwin 的 ARM GCC : fatal error: no input file

ubuntu - 如果内存和交换用完,进程是否会自动终止?

.net - 假装 .NET 字符串是值类型

c - 错误 : could not insert module. 模块中的未知符号

c - 在没有并行编程的情况下优化 C 代码

c - C中链表的合并排序代码仅对一半元素进行排序

string - 交换字符串中的字符

sql - 如何删除从 SQL 查询获取的以下数据中的交换列?

Python - 按值和按引用函数参数

c++ - 在C++中可以做 “call by reference when possible”吗?