1

For example:

  • temp->next = NULL is same as (*temp).next = NULL
  • list->next->next = temp is same as ??
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Side note: something line `list->next->next` is always wrong if we're talking linked lists. If `list->next` is NULL, `list->next->next` will trigger undefined behaviour (most likely some crash). – Jabberwocky May 13 '22 at 09:11
  • @Jabberwocky: "always" ? No. If you know that `list->next` points to a valid item, there is no problem. This construct can be met when you want to delete an element from a list. –  May 13 '22 at 09:20
  • @YvesDaoust I should have written "_is **almost** always wrong_". I've seen this often if buggy code that tries to delete a noide from a linked list, and it fails if the last node is to be deleted. – Jabberwocky May 13 '22 at 09:51
  • @Jabberwocky: what about "is dangerous" ? (Note that `list->next` can be dangerous as well.) –  May 13 '22 at 09:52
  • @YvesDaoust last comment edited. Yes of course `list->next` can be dangerous, but if `list` is invalid, there are serious other ponblems in the code. – Jabberwocky May 13 '22 at 09:58
  • @Jabberwocky: er, in most linked list traversals, the running pointer ends-up being null. –  May 13 '22 at 10:05

4 Answers4

2

It's the same as (*(*list).next).next = temp

tstanisl
  • 13,520
  • 2
  • 25
  • 40
0

This line

list->next->next = temp;

can be rewritten in several ways. For example

( *list ).next->next = temp;

or

( *( *list ).next ).next = temp;

or

( *list ->next ).next = temp;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0
temp->next = NULL;
(*temp).next = NULL;

Both lines are equivilent (assigning NULL to the value of next). The difference is that in the second, the pointer is dereferenced ((*temp)), which means we access the property with . instead of ->.

The operator -> is 'dereference'. It's specifically there to save you from the verbosity of dereferencing through *, especially when you often need the parentheses to make it work as intended. So do it like that.

list->next->next = temp;

This assigns the value of temp to the next property of the next list item. This might fail if list or list->next isn't a pointer to a valid memory location (such as NULL).

And when I say 'fail', I mean the behaviour is undocumented, because you will just be writing over something (some runtimes will catch assignment to NULL) that will likely cause hard to predict behaviour. It might appear to work now, and come and bite you later. They can be tricky to find, so pay attention ;-)

Generally, when assigning to a pointer, especially when chained in this way, make sure you have an appropriate guard condition/context to know that you can trust its doing the right thing.

if (list && list->next) {
  list->next->next = temp;
} else {
  // eek!
}
Dave Meehan
  • 3,133
  • 1
  • 17
  • 24
0

Same as

list[0].next[0].next= temp;