输出是“你好,世界”。我试图找出代码中发生的事情,并附上了一张图片 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;
}
世界,你好
关于c - 用于交换字符串的输出相关查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418567/