-3

I'm working with linked lists in C. Can someone please explain the function and purpose of:

t->next;

and

t.next;
  • Do you know what pointers are? If yes: `a->b` is syntactic sugar for `(*a).b`. So the `->` dereferences a pointer first, while `.` itself doesn't. `t.next` makes sense if `t` is a struct or class (`MyClass t`), `t->next` makes sense if `t` is a **pointer** to a struct/class (`MyClass* t`). If you don't know what pointers are: Please learn about them first, otherwise none of the explanations will make sense to you. – CherryDT Jul 18 '20 at 23:38
  • 1
    A C tutorial and book might be a good place to start: a_struct_pointer->member vs a_struct.member – user2864740 Jul 18 '20 at 23:38
  • What si `t` ? Both fragments assume a different definition... – wildplasser Jul 18 '20 at 23:38

1 Answers1

0

To access the member of the struct or union the . is used. To dereference pointer to the struct or union and access the member -> is used as in he examples blelow

struct node
{
    struct node *next;
};


void foo()
{
    struct node n;
    struct node *np = &n;
     
    // accessing member of the struct 
    n.next = &n;
    // accessing member of the struct via the pointer
    np -> next = &n;

    // accessing member of the struct via the derefenced pointer
    (*np).next = &n;

    (&n) -> next = &n;
}
0___________
  • 60,014
  • 4
  • 34
  • 74