allignment in structures
Eljay Love-Jensen
eljay@adobe.com
Thu Aug 26 16:19:00 GMT 2004
Hi Purnendu,
>A sizeof( struct abc) gives 3, shouldnot i expect it to be 4?
No, it should be 3 in this case.
The char data type has an alignment of 1.
#pragma pack(2) does not increase alignment requirements, it only decreases
them.
>any pointers???
Use GCC __attribute__ with aligned and pack to affect alignment and/or
packing, don't use #pragma pack.
// C++ example.
#include <cstdio>
#include <cstddef>
struct Foo
{
char a __attribute__((aligned(2)));
char b __attribute__((aligned(2)));
long c __attribute__((packed));
char d;
char e;
};
int main()
{
printf("Foo.a %d\n", offsetof(Foo, a));
printf("Foo.b %d\n", offsetof(Foo, b));
printf("Foo.c %d\n", offsetof(Foo, c));
printf("Foo.d %d\n", offsetof(Foo, d));
printf("Foo.e %d\n", offsetof(Foo, e));
}
Note: the aligned attribute has certain restrictions, depending on
platform. See the online documentation.
Often, alignment and packing are used to mimic a canonical data structure,
which populates the structure using read or fread. I strongly discourage
that practice, and encourage having a helper read routine that populates
the structure field-by-field from the byte-by-byte data source. Likewise,
the inverse for the write routines.
HTH,
--Eljay
More information about the Gcc-help
mailing list