3 ms·
It should be perfectly fine to do this: union reinterpret { char raw[100]; struct myStruct interpreted; } example; read(fd, &example.raw) stru
by tsimionescu 6y ago
It should be perfectly fine to do this:
union reinterpret {
char raw[100];
struct myStruct interpreted;
} example;
read(fd, &example.raw)
struct myStruct dest = interpreted;
This is standard-compliant C code, and it is a common way of reading IP addresses from packets, for example.
- saagarjha 6y ago(It should be noted that this is not valid C++ code.)
- jart 6y agoSensitive emotional subjects shouldn't be noted. Reminding C developers of the void* incompatibility is a good way to get them to feel triggered because it makes the language unpleasant.
- deleted 6y ago[deleted]
- jart 6y agoYou don't even need to pun that. It's legal to say: struct myStruct example; read(fd, &example, sizeof(example)); That "should present no problem unless binary data written by one implementation are read by another" quoth ANSI X3.159-1988. One example of a time where I've used that, is when storing intermediary build artifacts. Those artifacts only exist on the host machine. If the binary that writes/reads those artifacts gets recompiled, then the Makefile will invalidate the artifacts so they're regenerated. Since flags like -mstructure-size-boundary=n do exist and ABI breakages have happened with structs in the past.