简体   繁体   English

C 在函数中传递和重新分配指针

[英]C Passing and Reassinging Pointers in Functions

Here's the function in question.这是有问题的功能。 Why does x not change, despite having ptr reference it's memory address?尽管 ptr 引用了它的内存地址,为什么 x 不会改变? Similarly why doesn't y change?同样为什么 y 没有改变?

#include <stdio.h>


int func (int a, int *b)
{
  int *ptr = &a;
  *ptr += 5;
  ptr = b;
  *ptr -= 3;
  return a;
}

int main ()
{
  int x = 2;
  int y = 8;
  int ret = func (x, &y);
  printf ("x: %d\n", x);
  printf ("y: %d\n", y);
  printf ("ret: %d\n", ret);
  return 0;
}

Edit: yes y does change.编辑:是的,你确实改变了。 Sorry.对不起。

int func (int a, int *b)

'a' is passed by value. 'a' 是按值传递的。 Inside func() a has its own memory allocated, so anything you do to it does not affect the variable that was passed in. 'b' is a pointer to an int so changing the data at that address is still visible outside the scope of func().在 func() a 内部分配了自己的内存,因此您对其执行的任何操作都不会影响传入的变量。 'b' 是一个指向 int 的指针,因此更改该地址处的数据在范围之外仍然可见函数()。 Hence, x doesn't change, but y does.因此,x 不会改变,但 y 会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM