为什么地址不一样?

时间:2019-08-18 16:50:28

标签: 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);    
}

此处,&i&k地址不同,尽管k保留了i的值...

这是因为在函数声明k之后需要单独的内存分配吗?请向我解释!

3 个答案:

答案 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;
}