this is my struct :
struct Node {
struct Node* data;
struct Node* links[4];
}
assuming there is no padding, does Node->links[-1]
guaranteed to be pointing on Node::data
?
No guarantee; this is undefined behaviour:
In practice, it's quite possible that you will end up pointing at data
, but any attempts to access it will result in UB.
Array subscripting is defined in terms of pointer arithmetic, and the C99 standard has this to say about pointer arithmetic:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
So accessing Node->links[-1]
(even just getting the address of Node->links[-1]
) is undefined behavior, strictly speaking. So you have no guarantee that Node->links[-1]
will get you Node::data
.
But as many commentators mention, it will work pretty much always. I'd still consider it poor programming practice that should be avoided. If not for the technicality, then because it requires that modifications to struct Node
can easily cause bugs that the compiler will not help you with. When someone adds something between data
and links
, things will mysteriously break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With