'What is cryptic line of code for this statement? [closed]
For example:
temp->next = NULL
is same as(*temp).next = NULL
list->next->next = temp
is same as ??
Solution 1:[1]
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;
Solution 2:[2]
It's the same as (*(*list).next).next = temp
Solution 3:[3]
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!
}
Solution 4:[4]
Same as
list[0].next[0].next= temp;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | tstanisl |
Solution 3 | Dave Meehan |
Solution 4 | Yves Daoust |