Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I modify the swap function this way?

what happens when we modify the swap function this way ? I know it doesn't work but what exactly is going on ? I'm not understanding what I actually did ?

#include <stdio.h>

void swap(int*, int*);

int main(){
   int x=5,y=10;
   swap(&x, &y);
   printf("x:%d,y:%d\n",x,y);
   return 0;
 }

void swap(int *x, int *y){ 
   int* temp;
   temp=x;
   x=y;
   y=temp;
}
like image 660
Snape Avatar asked Dec 02 '22 09:12

Snape


1 Answers

In the function

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

you just swap the pointer values for the two function arguments.

If you want to swap their values you need to implement it like

void swap(int* x, int* y){ 
    int temp = *x;  // retrive the value that x poitns to
    *x = *y;        // write the value y points to, to the memory location x points to
    *y = temp;      // write the value of tmp, to the memory location x points to
}

that way the swap function swaps the value for the referenced memory locations.

like image 80
Ackdari Avatar answered Dec 27 '22 01:12

Ackdari