c - 用于交换字符串的输出相关查询

标签 c pointers swap

输出是“你好,世界”。我试图找出代码中发生的事情,并附上了一张图片 showing what the function should be doing according to me .但是我不明白为什么最终输出是这样的。

#include <stdio.h>

void func(char *p, char **q)
{
    char *temp = p;
    p = q;
    q = temp;
}

int main()
{
    char *p ="hello";
    char *q ="world";
    func(p,&q);
    printf("%s, %s", p, q);
    return 0;
}

最佳答案

您正在尝试通过引用传递来交换字符串,并且正在使用指针来这样做——这是正确的做法!但是,由于这是 C 语言中的字符串,您的实际变量是指针。这些指针地址按值传递(和交换)。实际上,如果您在 func 中放置一个打印函数,您会看到字符串的打印顺序与您期望的相反。

void func(char *p, char *q)
{
    char *temp = p;
    p = q;
    q = temp;
    printf("%s, %s", p, q);
}

int main()
{
    char *p ="hello";
    char *q ="world";
    func(p,q);
    printf("%s, %s", p, q);
    return 0;
}

世界,hellohello,世界

如果你想交换两个变量,你只需要传递它们的指针并交换它们 - 但如果你想交换指针本身,你需要传递对指针的引用。

#include <stdio.h>

void func(char **p, char **q)
{
    char *temp = *p;
    *p = *q;
    *q = temp;
}

int main()
{
    char *p ="hello";
    char *q ="world";
    func(&p,&q);
    printf("%s, %s", p, q);
    return 0;
}

世界,你好

Demo

关于c - 用于交换字符串的输出相关查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418567/

相关文章:

c++ - 编译具有特定体系结构的 C 程序

c++ - static_cast<const A>(*this) 和 static_cast<const A&>(*this) 的区别

javascript - JavaScript 中的图像交换?

c - 交换两个数字 - 处理器行为

c++ - 一种交换 vector 的方法,可能吗?

c - 嵌套范围如何影响堆栈深度?

c - 读写并发

c - gsoap/valgrind;没有泄漏,但内存错误

c++ - 创建指向类的指针的函数

python - 访问Python对象指针数据