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);
}
此处,&i
和&k
地址不同,尽管k
保留了i
的值...
这是因为在函数声明k
之后需要单独的内存分配吗?请向我解释!
答案 0 :(得分:7)
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
中更改了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
,这是一种更便携的打印指针的方法。
答案 1 :(得分:5)
^(?!.*[ ,'’]$)(?![ .,'’])[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'’-]+$
是k
的副本。
这是一个不同的变量。如果您修改i
,则k
不会受到影响。
答案 2 :(得分:0)
您正在传递价值。所以k是i的副本 如果您想访问相同的内容,则按引用通过
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)
{
*k = 1;
}