指针输出代码。我得到的答案恰恰相反。请解释一下这是怎么发生的
#include<iostream>
using namespace std;
//swap function
void swap (char *x, char *y)
{
char *t = x;
x = y;
y = t;
}
int main()
{
char *x = "geeksquiz";
char *y = "geeksforgeeks";
char *t;
swap(x, y);
cout<<x << " "<<y;
t = x;
x = y;
y = t;
cout<<" "<<x<< " "<<y;
return 0;
}
#include<iostream>
using namespace std;
//swap function
void swap (char *x, char *y)
{
char *t = x;
x = y;
y = t;
}
int main()
{
char *x = "geeksquiz";
char *y = "geeksforgeeks";
char *t;
swap(x, y);
cout<<x << " "<<y;
t = x;
x = y;
y = t;
cout<<" "<<x<< " "<<y;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您实现的交换函数中,您正在修改局部x和y,这对主函数中的x和y没有影响。有两种解决方案。
1- 为参数添加另一层指针:
然后调用函数
swap_pointer(&x, &y);
2- 将函数参数更改为引用类型:
然后调用该函数作为
swap_reference(x, y);
In the swap function that you have implemented, you are modifying local x and y, which has no effect on the x and y in the main function. There are two solutions for that.
1- Adding another level of pointer to the parameters:
and then calling the function as
swap_pointer(&x, &y);
2- changing the function parameters to reference types:
and then calling the function as
swap_reference(x, y);
您的代码有 2 个主要问题,解释如下:
问题 1
在 C++ 中,我们不能让
char*
指向字符串文字。这意味着,程序中的以下语句是无效:问题 1 的解决方案
为了解决这个问题,我们必须向指针添加一个低级常量,如下所示:
问题 2
除了上述问题之外,程序中名为
swap
的函数还采用按值作为参数。这意味着,您对函数内的这些参数所做的任何更改都不会反映在原始传递的参数上。这反过来意味着您实际上是在副本上执行交换,而不是在原始参数上执行交换,这解释了为什么您没有得到预期结果。问题 2 的解决方案
您可以通过通过引用传递参数来解决此问题,这可以通过使参数引用
const char*
来完成如下所示:工作演示
替代解决方案
请注意,您还可以使用
std::string
而不是使用指针如下图:Demo
There are 2 main problems with your code both of which are explained below:
Problem 1
In C++, we cannot have
char*
pointing to a string literal. This means, the following statements in your program are invalid:Solution to Problem 1
To solve this, we have to add a low-level const to the pointers as shown below:
Problem 2
In addition to the above problem, the function named
swap
in your program takes argument by value. This means, whatever changes you make to those arguments inside the function will not be reflected back on the original passed arguments. This in turn means that you're actually performing a swap on the copies and not on the original arguments which explains why you don't get your expected result.Solution to Problem 2
You can solve this by passing the argument by reference which can be done by making the parameter to be reference to
const char*
as shown below:Working demo
Alternative solution
Note that you can also use
std::string
instead of using pointers as shown below:Demo