#include <stdlib.h>
int swap(int a,int b);
int main() {
int x,y;
printf("Enter the first integer:"); scanf("%d",&x);
printf("Enter the second integer:"); scanf("%d",&y);
printf("\nBefore swap: x=%d, y=%d\n",x,y);
swap(x,y);
printf("After swap: x=%d, y=%d",x,y);
return 0;
}
int swap(int a, int b){
int temp;
temp = a;
a=b;
b=temp;
}
This is my code to swap 2 integers entered by the user but it doesn't work although everything seems to be in order. However if I change my code to this using pointers, it does.
#include <stdlib.h>
int swap(int *,int *);
int main() {
int x,y;
printf("Enter the first integer:"); scanf("%d",&x);
printf("Enter the second integer:"); scanf("%d",&y);
printf("\nBefore swap: x=%d, y=%d\n",x,y);
swap(&x,&y);
printf("After swap: x=%d, y=%d",x,y);
return 0;
}
int swap(int *a, int *b){
int temp;
temp = *a;
*a=*b;
*b=temp;
}
I would really appreciate if anyone could explain me why and how it worked with pointers but why it didn't without pointers.