Hi,
If I run the code below I get the following output :-
Sizeof struct A 1
Sizeof struct B 4
Sizeof struct C 8
Sizeof struct D 224
I would have thought the values would be :-
Sizeof struct A 1
Sizeof struct B 4
Sizeof struct C 5
Sizeof struct D 223
Whats up ?
typedef struct {
char a;
} A;
typedef struct {
int b;
} B;
typedef struct {
char a;
int b;
} C;
typedef struct {
char a[21];
short b[100];
short n;
} D;
int main(int argc, char *argv[]) {
printf(“Sizeof struct A %d \n”, sizeof(A));
printf(“Sizeof struct B %d \n”, sizeof(B));
printf(“Sizeof struct C %d \n”, sizeof(C));
printf(“Sizeof struct D %d \n”, sizeof(D));
return EXIT_SUCCESS;
}
Brett Wilton <bdwilton@xtra.co.nz > wrote:
Hi,
If I run the code below I get the following output :-
The compiler is free to pad and resize your structs to make alignment
work out better. In some cases, this alignment is required as there
are CPUs that do not tolerate unaligned accesses (ARM for example).
chris
–
Chris McKillop <cdm@qnx.com > “The faster I go, the behinder I get.”
Software Engineer, QSSL – Lewis Carroll –
http://qnx.wox.org/
system
July 16, 2003, 8:49pm
3
If you need some structures to be packed (specially,
if they should be binary compatible to QNX4 structures)
you could use ‘#pragma pack(1)’:
Brett Wilton <bdwilton@xtra.co.nz > wrote:
#pragma pack(1)
typedef struct {
char a;
int b;
} C;
#pragma pack()
#pragma pack(1)
typedef struct {
char a[21];
short b[100];
short n;
} D;
#pragma pack()
Then the structures wile have the sizes you expect (though they may
not have optimal size ).
–
| / | __ ) | Karsten.Hoffmann@mbs-software.de MBS-GmbH
| |/| | _ _ \ Phone : +49-2151-7294-38 Karsten Hoffmann
| | | | | ) |__) | Fax : +49-2151-7294-50 Roemerstrasse 15
|| | |/ / Mobile: +49-172-3812373 D-47809 Krefeld
Brett Wilton <bdwilton@xtra.co.nz > wrote:
Hi,
If I run the code below I get the following output :-
Sizeof struct C 8
Sizeof struct D 224
I would have thought the values would be :-
Sizeof struct C 5
Sizeof struct D 223
Whats up ?
typedef struct {
char a;
You have a 4-byte value, it will be put on a 4-byte boundary,
giving you a bonus 3 bytes of padding after char a;
int b;
} C;
typedef struct {
char a[21];
You have a 2-byte value, it will be put on a 2-byte boundary,
giving you a bonus byte of padding after char a[21];
short b[100];
short n;
} D;
You can use pack pragmas to turn off this behaviour – but you
may not want to.
For the following structure – if you force it to 5 bytes (
pack 1):
typedef struct {
char a;
int b;
} C;
And you try to access b, on many platforms (e.g. ARM, PPC), this will
give you a SIGBUS error.
On other platforms (e.g. x86) it will just be a lot slower instead.
-David
QNX Training Services
http://www.qnx.com/support/training/
Please followup in this newsgroup if you have further questions.