gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:49:19 24 4
gpt4 key购买 nike

输出是“你好,世界”。我试图找出代码中发生的事情,并附上了一张图片 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com