[英]why swapping value using pointer doesn't work?
I have written the following code. 我写了下面的代码。 It should swap the values of two variables ... but, as soon as I compile the code it shows swap.exe has stopped working...
它应该交换两个变量的值...但是,一旦我编译代码,它表明swap.exe已经停止工作...
Why doesn't it work? 为什么不起作用?
#include<cstdio>
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int *temp;
*temp=*x;
*x=*y;
*y=*temp;
}
int main()
{
int i=5,j=10;
swap(&i,&j);
cout<<i<<" "<<j<<endl;
return 0;
}
How to fix this problem? 如何解决这个问题? What's wrong with my code?
我的代码有什么问题?
Change to 改成
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
If you want to swap two int
s why do you use a pointer to int
as temporary variable? 如果要交换两个
int
为什么要使用指向int
的指针作为临时变量? Use the same type. 使用相同的类型。
Because temp
is a dangling pointer, so accessing *temp
is undefined behavior. 因为
temp
是一个悬空的指针,所以访问*temp
是未定义的行为。
You can use int temp;
您可以使用
int temp;
and temp = *x; ...
和
temp = *x; ...
temp = *x; ...
, or just use std::swap
. temp = *x; ...
,或只使用std::swap
。
It does not work, because you copy the content of x
to a location that is pointed by an uninitialized pointer ( temp
). 它不起作用,因为您将
x
的内容复制到了未初始化的指针( temp
)指向的位置。
If you simply want to swap the contents of x
and y
you may use std::swap(*x, *y)
. 如果只想交换
x
和y
的内容,则可以使用std::swap(*x, *y)
。
use temp as int not as int * as in: 使用temp作为int而不是int *,如下所示:
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
declare int temp
as just a int type variable, not a pointer. 将
int temp
声明为int类型变量,而不是指针。 Because you are just storing value of x in temp, not pointing to x. 因为您只是在温度中存储x的值,而不是指向x。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.