在功能中使用指针
为什么每次您在功能内部声明指针参数并开始在功能中使用它时,每次您在函数中以某种方式使用它时都需要在指针变量旁边使用星号。为什么这样?
Why is it that everytime you declare pointer parameter inside the function and start to use it inside the function, you need to use asterisk next to the pointer variable everytime you use it somehow in the function. Why is it that way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您来自像Java这样的语言,您可以在其中进行:
您基本上看到您唯一可以使用
w
参考(例如derference it(例如呼叫方法))来对其进行测试。代码> null 。这是足够微不足道的,您不需要任何额外的语法即可使用参考。
但是,在C和C ++中,您可以拥有以下内容:
(*P)++
和p ++
:前者在该值上运行,就像在Java,而后者则在指针上运行。总而言之,由于C和C ++允许您用指针做更多的事情,而不是Java和C#等语言,所以指针需要某种额外的语法。
您可能会问“为什么不将“简单”语法(例如在Java中)解释,并需要这些其他指针操作的额外语法?”。我不确定,但是,但是在没有任何进一步操作的情况下,取消指针的行为是其自己的操作(可能会表现出来),因此将其赋予额外的语法似乎是合适的。
If you come from a language like Java, where you do:
You basically see that the only things you can do with the
w
reference, besides dereference it (e.g. call methods), is to test it againstnull
.That is trivial enough that you don't need any extra syntax to work with references.
In C and C++, however, you can have the following:
There is a critical difference between
(*p)++
andp++
: the former operates on the value, like in Java, whereas the latter operates on the pointer.In summary, because C and C++ allow you to do many more things with pointers than languages like Java and C#, pointers require some kind of extra syntax.
You could ask "why not make dereference the "easy" syntax (like in Java) and require the extra syntax for these other pointer operations?". I don't know for sure, but but the very act of dereferencing a pointer, without any further operation on it, is its own an operation (which could segfault), so it seems appropriate to give it the extra syntax.
因为这就是指针在C中工作的方式 - 访问指向对象,因此您使用Unary
*
运算符删除指针。它不是自动的,因为有时您想使用指针值本身。
Because that's how pointers work in C - to access the pointed-to object, you dereference the pointer using the unary
*
operator.It's not automatic because sometimes you want to work with the pointer value itself.