-3 c
void test(int k);
int main()
{
int i = 0;
printf("The address of i is %x\n", &i);
test(i);
printf("The address of i is %x\n", &i);
test(i);
return 0;
}
void test(int k)
{
print("The address of k is %x\n", &k);
}
Run Code Online (Sandbox Code Playgroud)
在这里,&i和&k地址虽然k保留了i... 的值,但地址却不同。
这是因为函数声明后k需要单独的内存分配吗?请向我解释!
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);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们更改kin函数的值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
Run Code Online (Sandbox Code Playgroud)
我还使用了%p,这是一种更便携的打印指针的方法。