几节课之前,我学习了变量,并在我的作业中提出了一个关于交换两个数字的问题 - 我使用了第三个变量来解决这个问题。
解决方案看起来有点像这样:
#include <stdio.h>
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
// swappring the values
int temp = x;
x = y;
y = temp;
printf("X is now %d and Y is now %d", x, y);
}
现在我正在学习函数,我想尝试使用辅助交换函数解决上一个问题。
这是我写的代码:
#include <stdio.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main(void) {
int a = 3, b = 4;
swap(a, b);
printf("%d %d\n", a, b);
}
我不知道为什么,但即使我更改了3 4
函数内的值,输出仍然是swap()
。
为什么会这样?
传递x
和y
的地址作为函数的参数。现在它们是局部变量,不会对原始变量进行更改。
做如下 -
void swap(int *x,int *y){
/* dereference pointers and swap */
int temp = *x;
*x = *y;
*y = temp;
}
并像这样在main
打电话 -
swap(&x,&y);
你正在做的是按值传递参数。这意味着在函数调用期间,将创建参数的副本。因此,在函数内部,您正在处理实际变量的副本。
相反,您需要将其作为参考传递。请阅读有关按值传递与按引用传递的更多信息。
#include <stdio.h>
void swap(int& x,int& y) //Instead of passing by value just pass by reference
{
int temp=x;
x=y;
t=yemp;
}
int main() {
int a=3,b=4;
swap(a,b);
printf("%d %d\n",a,b);
return 0;
}
编辑:C没有参考。上面的代码将在c ++中使用。要在C中工作,只需使用指针并在函数内取消引用它。