C 使用按值传递。这意味着该函数test
接收传递给它的值的副本。
为了更清楚地看到这一点,您可以查看值和地址:
int main()
{
int i = 0;
printf("The address of i is %p and the value is %d\n", &i, i);
test(i);
printf("The address of i is %p and the value is %d\n", &i, i);
return 0;
}
void test(int k)
{
printf("The address of k is %p and the value is %d\n", &k, k);
k = 1;
printf("The address of k is %p and the value is %d\n", &k, k);
}
这里我们改变了k
in function的值test
,但这并没有改变i
调用者的值。在我的机器上打印:
The address of i is 0x7ffee60bca48 and the value is 0
The address of k is 0x7ffee60bca2c and the value is 0
The address of k is 0x7ffee60bca2c and the value is 1
The address of i is 0x7ffee60bca48 and the value is 0
我也使用过%p
,这是一种更便携的打印指针的方式。