when I try to swap these two integers using pointers, I get segmentation fault.
Basically before I swap, x
is assigned to 1
and y
is assigned to 2
. After I swap x
is assigned to 2
and y
is assigned to 1
.
The program takes two integers x
and y
and is supposedly meant to swap them:
int swap(int x, int y){
int *swapXtoY;
int *swapYtoX;
*swapXtoY = y;
*swapYtoX = x;
}
Function swap
is expecting both of its argument as int
, but you are passing int *
. Compiler should raise a warning about this.
It seems that you have no idea how pointers work in C. Your function is just assigning two int
s to local variables. Function should be like:
int swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
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