Using arrow -> and dot . operators together in C

二次信任 提交于 2019-12-03 05:08:34

问题


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".


回答1:


Use -> for pointers; use . for objects.

In your specific case you want

if (sample->left->num > sample->right->num)

because all of sample, sample->left, and sample->right are pointers.

If you convert any of those pointers in the pointed to object; use . instead

struct a copyright;
copyright = *(sample->right);
// if (sample->left->num > copyright.num)
if (*(sample->left).num > copyright.num)



回答2:


Since I don't see it mentioned explicitly:

  • Use -> to dereference the pointer on its left hand side and access the member on its right hand side.
  • Use . to access the member on its right hand side of the variable on its left hand side.



回答3:


sample->left gives a struct a*, not a struct a, so we're dealing with pointers. So you still have to use ->.

You can, however, use sample->left->num.




回答4:


. is for accessing the members of a struct (or union) e.g.

struct S {
int x;
}

S test;
test.x;

-> is a shorter way to write (*pointer_to_struct).struct_member




回答5:


sample->left and sample->right are also pointers, so you want:

if (sample->left->num > sample->right->num) {
    // do something
}


来源:https://stackoverflow.com/questions/5844972/using-arrow-and-dot-operators-together-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!