#include <stdio.h>
int f1(int *x, int y) {
y++;
(*x)++;
return *x + y;
}
int main() {
int x = 10, y = 5;
int z = f1(&x, y);
printf("x=%d y=%d z=%dn", x, y, z);
}
我得到的答案是x=11 y=5 z=17
。有人能解释一下吗?
检查注释。
#include <stdio.h>
int f1(int *x,int y)
{
y++; // incrementing y, which was 5, to 6.
(*x)++; // incrementing the value-at-address-x, which was 10, to 11
return *x+y; // add value-at-address-x, 11, and value of y, 6 == 17, return that.
}
int main(void) //correct signature of main in hosted environment
{
int x=10,y=5;
int z=f1(&x,y);
//any changes made to the value stored at address x will reflect here,
// any changes made to the value of y will be local to the function call.
printf("x=%d y=%d z=%dn",x,y,z);
// updated x, unchanged y, and returned z.
}
f1
中的形式参数x
和y
是内存中与main
中的变量x
和y
不同的对象。
当您调用z=f1(&x, y);
时,表达式&x
和y
将被完全求值,并且这些表达式的结果被复制到形式参数x
和y
(这就是我们说C按值传递函数参数时的意思(。
因此,形式参数x
存储变量x
的地址,而形式参数y
存储值5
。
由于形式参数y
与变量y
在内存中是不同的对象,因此更改其值对main
中的y
没有影响。
表达式*x
是f1
在某种程度上充当变量x
的别名,因此更改f1
中*x
的值会更改main
中x
的值。