#include <stdio.h>
void swap(int* x, int* y){
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
int x = 2, y =3;
swap(&x, &y);
return 0;
}
Output: The value of x and y inside the function is x = 6422300 and y = 6422296
Why the value of x is 6422300 and y is 6422296 inside the function?
#include <stdio.h>
void swap(int* x, int* y){
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
int x = 2, y =3;
swap(&x,&y);
printf("\nThe value of x and y in the main is x = %d and y = %d", x, y);
return 0;
}
Output: The value of x and y inside the function is x = 6422300 and y = 6422296 The value of x and y in the main is x = 3 and y = 2
I tried to write the print statement for x and y in main separately, then it worked properly. But why it wasn't working inside function?
Your code invoked undefined behaviour as you pass the pointer not the integer to the
printf.%dis expectingint. You need to dereferencexandy