Khairul Basar Rofi Khairul Basar Rofi - 3 months ago 8
C Question

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...

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?

Answer

Change to

void swap(int *x, int *y)
{
    int temp;
    temp=*x;
    *x=*y;
    *y=temp;
}

If you want to swap two ints why do you use a pointer to int as temporary variable? Use the same type.