使用箭头->和点 . C 中的运算符在一起
我的印象是,可以通过像这样一起使用箭头和点运算符来从链表或类似结构的子节点访问数据:
typedef struct a{
int num;
struct a *left;
struct a *right;
}tree;
tree *sample;
...
if(sample->left.num > sample->right.num)
//do something
但是当我尝试实现这一点时,使用 ->;和 。要从子节点访问数据,我收到错误“请求非结构或联合中的成员 num”。
I was under the impression that it was possible to access data from a sub-node of a linked list or similar structure by using the arrow and dot operators together like so:
typedef struct a{
int num;
struct a *left;
struct a *right;
}tree;
tree *sample;
...
if(sample->left.num > sample->right.num)
//do something
but when I try to implement this, using -> and . to access data from a sub node I get the error "request for member num in something not a structure or union".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
->
作为指针;使用.
表示对象。在您的具体情况下,您需要
,因为所有
sample
、sample->left
和sample->right
都是指针。如果您转换指向对象中的任何指针;使用
.
代替Use
->
for pointers; use.
for objects.In your specific case you want
because all of
sample
,sample->left
, andsample->right
are pointers.If you convert any of those pointers in the pointed to object; use
.
instead因为我没有看到明确提到它:
Since I don't see it mentioned explicitly:
。用于访问结构(或联合)的成员,例如
->是一种更短的写法 (*pointer_to_struct).struct_member
. is for accessing the members of a struct (or union) e.g.
-> is a shorter way to write (*pointer_to_struct).struct_member
Sample->left 给出一个 struct a*,而不是一个 struct a,所以我们处理的是指针。
所以你还是要使用
->
。不过,您可以使用
sample->left->num
。sample->left gives a
struct a*
, not astruct a
, so we're dealing with pointers.So you still have to use
->
.You can, however, use
sample->left->num
.sample->left
和sample->right
也是指针,所以你想要:sample->left
andsample->right
are also pointers, so you want: