Using arrow -> and dot . operators together in C

后端 未结 5 1426
灰色年华
灰色年华 2021-02-01 07:51

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:

相关标签:
5条回答
  • 2021-02-01 08:13

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

    if (sample->left->num > sample->right->num) {
        // do something
    }
    
    0 讨论(0)
  • 2021-02-01 08:18

    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.
    0 讨论(0)
  • 2021-02-01 08:19

    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.

    0 讨论(0)
  • 2021-02-01 08:24

    . 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

    0 讨论(0)
  • 2021-02-01 08:27

    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)
    
    0 讨论(0)
提交回复
热议问题