What is the correct way to access packed struct's members?
struct __attribute__ ((packed)) MyData {
char ch;
int i;
}
void g(int *x); // do something with x
void foo(MyData m) {
g(&m.i);
}
void bar(MyData m) {
int x = m.i;
g(&x);
}
My IDE gives warning/suggestion for foo that I might be accessing misaligned int pointer, which is indeed the case here. My questions are
- Between foo and bar, is one approach better than the other?
- Is it incorrect to access misaligned pointer data but okay to use it to initialize a properly aligned type? (as in bar).
- Should we copy packed struct individual members to properly aligned data structure and then use it? That would imply that for almost every packed data structure there is a non-packed data structure and packed structure remains confined to serialization layer.