C传递指向函数混淆的指针 [英] C passing pointer to a function confusion

查看:78
本文介绍了C传递指向函数混淆的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有点困惑.这是一本很棒的 C 书,也许我对它的质疑太多了,但不知何故它没有意义.我希望我能说出我的困惑.

I am a bit confused here. This is from a great C book, and maybe I question it too much, but somehow it didn't make sense. I hope I can tell my confusion.

假设下面&a指向内存地址87,&b指向内存地址120;

Let's say below &a points to the memory address 87 and &b points to the memory address 120;

int a = 3;
int b = 4;
swap(&a, &b);

void swap(int *px, int *py) {
   int temp;
   temp = *px;
   *px = *py;
   *py = temp;
}

好的,问题来了:当我们调用函数swap并将参数传递给函数时我们实际上是将px"设置为87还是将*px"设置为87?

OK, here is the question: When we call function swap and pass the parameters to the function are we actually setting "px" to 87 or are we setting "*px" to 87?

因为如果我们将 *px 设置为 87 那么根据 * 符号的定义,我们设置的是指针指向的值,而不是 p 持有的内存地址,这在这个例子.另一方面,如果我们实际上将p"设置为 87,那么 swap 中的代码是有意义的,因为当我们在函数中使用 * 符号时,我们将引用该地址中的值3"这里.但是为什么语法令人困惑并且看起来好像我们正在设置

Because if we are setting *px to 87 then by definition of the * sign, we are setting the value where the pointer refers to, but not the memory address p holds, which is wrong in this example. On the other hand, if there we are actually setting "p" to 87 then the code in swap makes sense, because then when we use the * sign in the function we will be referring to the value in that address which is "3" here. But then why is the syntax confusing and looks like as if we are setting

*px = 87

?

推荐答案

* 可能意味着三个不同的事情,具体取决于上下文:

* may mean three different things, depending on the context:

  • a * b中,表示乘法.
  • int *a中,表示我们现在声明一个变量或参数a,其类型为int *(指向int).
  • *a中(假设*左边没有数据类型,所以这是一个表达式而不是一个declaration),意思是a 是一个指针,我们要查看它指向的值(也称为解除引用指针".
  • In a * b, it means multiplication.
  • In int *a, it means "we are now declaring a variable or parameter a, whose type is int * (pointer to int).
  • In *a (assuming that there is no data type to the left of *, so that this is an expression and not a declaration), it means "a is a pointer, and we want to look at the value it points to (also known as dereferencing the pointer".

所以你方法的参数是a,而不是*a;星号是参数类型的一部分,a 是您设置为 87 的内容.将指针声明编写为 int * aint* a> 而不是 int *a 可能有助于更清晰地区分声明和取消引用.

So the parameter to your method is a, not *a; the asterisk is part of the parameter's type, and a is what you are setting to 87. Writing pointer declarations as int * a or int* a instead of int *a may help making the distinction between declaration and dereferencing clearer.

这篇关于C传递指向函数混淆的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆