It's sometimes necessary to cast a data structure into a pointer so that the data can be sent, for example, over an interface, or written out to some other stream. In these cases, I usually do something like this:
typedef struct {
int field1;
char field2;
} testStruct;
int main()
{
char *buf;
testStruct test;
buf = (char *)&test;
// write(buf, sizeof(test)) or whatever you need to do
return 0;
}
Recently in some microprocessor code, however, I saw something similar to this:
typedef struct {
int field1;
char field2;
} testStruct;
int main()
{
char buf[5];
testStruct test;
*(testStruct *)buf = test;
// write(buf, sizeof(test)) or whatever you need to do
return 0;
}
To me, the former feels a little more safe. You just have one pointer, and you assign the address of the structure to the pointer.
In the latter case, it seems like if you allocate the wrong size to the array buf by accident, you'll end up with undefined behavior, or a segfault.
With optimizations on, I get a -Wstrict-aliasing warning from gcc. However, again, this code runs on a microprocessor, so is there something I might be missing there?
There's no pointers in the structures, or anything, it's very straight forward.
memcpyor deep copies in general. It's more about the correct way to cast a data structure to a buffer.(testStruct *)bufmay generate a mis-aligned address for atestStructleading to a bus fault. Do not use. Aunionis better.writeand friends use avoid *as a buffer argument so no cast is needed.write(fd, &test, sizeof(test))is perfectly OK, as long as you accounted for platform differences.*(testStruct *)buf = test;wouldn't pass a code review.*(testStruct *)buf = testis a bad idea (actually a pretty stupid idea, I'd say) because it needlessly copies data. If you havetest, but you just want to temporarily treat it as a blob o' bytes, then the equivalent ofbuf = (unsigned char *)&testis just what you want. (Or if you really want to copy data, callmemcpy. But a cast and a pretend struct assignment is just a bad idea, a holdover from the rough, roguish early days of C.)