|
|
|
|
|
by whizzter
254 days ago
|
|
Even better and simpler.. Payload *item = (Payload *)malloc(offsetof(Payload, elements[N]));
The rest of the article does make me vary of a lot of other things that aren't done "per-spec" if you're making your own container and probably will cause unintended bugs in the future. |
|
However, the traditional (and pretty much the only sensible) ways of defining offsetof do make it work.
N3220 draft:
[expands] to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the subobject (designated by member-designator), from the beginning of any object of type type. The type and member designator shall be such that given then the expression &(t. member-designator) evaluates to an address constant. If the specified type name contains a comma not between matching parentheses or if the specified member is a bit-field, the behavior is undefined.This doesn't mean I won't use it, but just something to be aware of.
It might not be a bad idea to propose to ISO C that offsetof(type, array[n]) should be required to work, and for non-constant n too.