when the compiler generates 32-bit code, it add "padding" elements struct members to make the fields easier to access in terms of run-time performance. The process of adding padding space is called"alignment".
In general, alignment modules=sizeof(type).
VC8.0 sets 1 as alignment modules for char, 2 for short, 4 for (int, long, float), and 8 for (long long, double).
GCC set 1 as alignment modules for char, 2 for short, 4 for the other types. The address is a multiple of alignment modules.
As a result, the struct size may be larger than the sum of members. So always use sizeof struct to read and write a structure. According to ANSI C, the bitfields are not certain to be stored in the specified order(actually GCC and VC is strictly ordered). Anyhow, it's a good habit to put big data behind.
Experiment:
struct s1{ char a; short b; double c; }; struct s2{ char a; double c; short b; };
|
Tested by VC 8.0 and MinGW,
sizeof(struct s1)=16, sizeof(struct s2)=24
Tested by GCC 4.3.2 on the Linux platform,
#include <stdio.h> #include <stdlib.h>
struct s1{ char a; short b; double c; }; struct s2{ char a; double c; short b; };
int main() {
struct s1 tmp1; struct s2 tmp2;
printf("sizeof(s1)=%d\n", sizeof(struct s1)); printf("address of &tmp1 is= %p\n", &tmp1); printf("address of tmp1->a= %p \t offset of tmp1->a= %lu\n", &tmp1.a, (long) &((struct s1 *)0)->a); printf("address of tmp1->b= %p \t offset of tmp1->b= %lu\n", &tmp1.b, (long) &((struct s1 *)0)->b); printf("address of tmp1->c= %p \t offset of tmp1->c= %lu\n\n", &tmp1.c, (long) &((struct s1 *)0)->c);
printf("sizeof(s2)=%d\n", sizeof(struct s2)); printf("address of &tmp2 is= %p\n", &tmp2); printf("address of tmp2->a= %p \t offset of tmp2->a= %lu\n", &tmp2.a, (long) &((struct s2 *)0)->a); printf("address of tmp2->c= %p \t offset of tmp2->c= %lu\n", &tmp2.c, (long) &((struct s2 *)0)->c); printf("address of tmp2->b= %p \t offset of tmp2->b= %lu\n\n", &tmp2.b, (long) &((struct s2 *)0)->b);
return 0; }
/* sizeof(s1)=12 address of &tmp1 is= 0xbfb387d8 address of tmp1->a= 0xbfb387d8 offset of tmp1->a= 0 address of tmp1->b= 0xbfb387da offset of tmp1->b= 2 address of tmp1->c= 0xbfb387dc offset of tmp1->c= 4
sizeof(s2)=16 address of &tmp2 is= 0xbfb387c8 address of tmp2->a= 0xbfb387c8 offset of tmp2->a= 0 address of tmp2->c= 0xbfb387cc offset of tmp2->c= 4 address of tmp2->b= 0xbfb387d4 offset of tmp2->b= 12 */
|
阅读(1820) | 评论(1) | 转发(0) |