Search code examples
c++powerpcpragma-pack

passing address of packed struct member


I am developing a C/C++ application where in I am using packed struct members. I have read that we should never pass address of packed struct members to any function(I always used to get alignment errors when passing packed struct members by reference to functions as arguments). So I want to know whether this applies even in the case of sscanf etc. inbuilt like functions. This is my code snippet

#pragma pack(push,1)
struct A
{
    char a;
    short b;
    int c;
};
#pragma pack(pop)

int main(int argc, char* argv[])
{
    struct A abc;
    char ch[100];
    ...
    //read some data from file into character array ch
    sscanf(ch,"%hu %d",&abc.b,&abc.c);
    ...

    return 0;
}

I am running my application of Power PC architecture.


Solution

  • sscanf accesses data fields like any other function, so if access to improperly aligned data causes an exception, sscanf will also fail. Some architectures however allow unaligned data, they just access such data slower than aligned ones.

    In general, assuming anything about data alignment is a bad practice that leads to very obscure errors. Just don't do that, there always is a better (and safer) way.