(type*)var
is generally a compiler error except if var
is an integer type. Integers may be converted to pointers by a special rule C17 6.3.2.3/5:
An integer may be converted to any pointer type. Except as previously specified, the
result is implementation-defined, might not be correctly aligned, might not point to an
entity of the referenced type, and might be a trap representation.
As for casting the address of a char
buffer to a pointer as in (struct inotify_event *)&buffer[i]
, the pointer conversion itself is allowed by C. Though this code is most likely a bug. There are several problems with this conversion:
buffer[i]
is not necessarily aligned, if not it's a misaligned access bug.
- Pointer types do not necessarily have the same size as the content pointed-at. And vice versa. For example storing a 32 bit value in a 64 bit pointer works, but not the other way around. That's why
uintptr_t
is the only safe integer type to use for such conversions.
- Should you de-reference this struct pointer or any of its members, it is likely a strict aliasing violation bug. What is the strict aliasing rule?
In case the article described a dirty hack, well then, it is just that. Dirty hacks aren't very stable or portable. Otherwise, if the article described the correct way of doing things, the author was probably not very familiar with intermediate level C programming.