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.