iLeoDo
iLeoDo

Reputation: 397

swap function didn't work

Why this swap method didn't work

void swap(int *x,int *y){

     int *temp;
     temp = x;
     x = y;
     y = temp;
}

Why? I think it's same as the common one..

Upvotes: 0

Views: 146

Answers (3)

sergio
sergio

Reputation: 69027

  1. x and y behave just like local variables.

  2. your code is swapping x and y values, not the values they point to.

Upvotes: 1

ouah
ouah

Reputation: 145839

C passes function arguments by value: you are only swapping copies of pointers.

If you want to swap two int:

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

Upvotes: 3

Gordon Bailey
Gordon Bailey

Reputation: 3911

You are swapping the addresses stored in temporary pointers on the stack, not the values stored in the memory they point to. You want to do this instead:

void swap(int *x,int *y){

     int temp = *x;
     *x = *y;
     *y = temp;
}

Upvotes: 1

Related Questions