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...
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? Use the same type.
Because temp
is a dangling pointer, so accessing *temp
is undefined behavior.
You can use int temp;
and temp = *x; ...
temp = *x; ...
, or just use std::swap
.
It does not work, because you copy the content of x
to a location that is pointed by an uninitialized pointer ( temp
).
If you simply want to swap the contents of x
and y
you may use std::swap(*x, *y)
.
use temp as int not as int * as in:
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. Because you are just storing value of x in temp, not pointing to x.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.