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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With