#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;
}
输出: 函数内 x 和 y 的值为 x = 6422300 和 y = 6422296
为什么函数内部x的值为6422300,y的值为6422296?
#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;
}
输出: 函数内 x 和 y 的值为 x = 6422300 和 y = 6422296 主要的 x 和 y 的值是 x = 3 和 y = 2
我尝试在main中分别编写x和y的打印语句,然后它工作正常。但为什么它在函数内部不起作用?
当您将指针而不是整数传递给
printf
时,您的代码调用了未定义的行为。 %d
正在期待int
。您需要取消引用 x
和 y
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);
}