-3
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需要单独的内存分配吗?请给我解释一下!

4

3 回答 3

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);
}

这里我们改变了kin 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,这是一种更便携的打印指针的方式。

于 2019-08-18T16:54:29.557 回答
5

ki.

这是一个不同的变量。如果修改ki不会受到影响。

于 2019-08-18T16:54:42.280 回答
0

你是按价值传递的。所以 k 是 i 的副本。如果你想访问相同的 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;
}
于 2019-08-18T20:06:56.900 回答