|
|
|
|
|
by metadat
712 days ago
|
|
That is amazing, isn't it? I want to understand, in: uint64_t sum5(Node *node) {
uint64_t value = 0;
Node *next = NULL;
for (; node; node = node->next) {
for (;;) {
value += node->value;
if (node + 1 != node->next) {
break;
}
node++;
}
}
return value;
}
How is this magic: if (node + 1 != node->next) {
break;
}
Better than the more intuitive: if (node->next == null) {
break;
}
Also.. why is `node + 1' even a valid comparison? (Please forgive my rusty C/C++, college was awhile ago) |
|
In C and C++, when you add 1 to a pointer, you actually make it point to the next object of that size in memory, e.g. if I have a pointer to a 4-byte integer at address 0x8000, incrementing it will make it point to address 0x8004.
Because arrays are contiguous chunks of memory, you can use this to iterate through arrays.
After this loop, p will be equal to &array[50], which is one past the last element of the array, because the loop will have run 50 times, and p is incremented once per loop.What OP did is allocate an array of linked list nodes, and test to see if the next linked list node was actually just the next array element.