#include <stdio.h>//gcc ubuntu 32-#pragma pack (8) typedef struct m{ char a ; long b ;} m;typedef struct n{ char a ; char b ; long c ;} N;typedef struct x{ char a ; struct m b ; long long c ;} X;typedef struct y{ char a ; struct n b ; long long c ;} Y; #pragma pack () #define &NBSP;&NBSP;ADDR (ADDR) ((Unsigned int) (ADDR)) Void main ( void) { printf ("sizeof (char):%d sizeof (short):%d sizeof (int):%D sizeof (Long):%d sizeof (Long long):%d\n ", sizeof (char), sizeof (short), sizeof (int), sizeof (long), sizeof (Long long)); printf ("sizeof (M):%d sizeof (N):%d sizeof (X):%d sizeof (Y):%d\n", sizeof (M), sizeof (N), sizeof (X), sizeof (Y)) ; M m ; n n ; x x ; y y ; printf ("m.a:%d m.b:%d \n", ADDR (&M.A)-ADDR (&m), ADDR (&M.B)-addr (&m)); printf ("n.a:%d n.b:%d n.c:%d \n ", ADDR (&N.A)-addr (&n), ADDR (&n.b)-addr (&n), ADDR (&N.C)-addr (&n)); printf ("x.a:%d x.b.a:%d x.b.b:%d x.c:%d\n", ADDR (&X.A)- ADDR (&x), ADDR (&X.B.A)-ADDR (&x), ADDR (&x.b.b)-addr (&x), ADDR (&X.C)-addr (&x)); printf ("y.a:% D y.b.a:%d y.b.b:%d y.b.c:%d y.c:%d\n ", ADDR (&Y.A)-addr (&y), ADDR (&Y.B.A)- ADDR (&y), ADDR (&y.b.b)-addr (&y), ADDR (&Y.B.C)-addr (&y), ADDR (&Y.C)-addr (&y)); return ;} /* Program run Result: sizeof (char): 1 sizeof (short): 2 sizeof (int): 4 sizeof (Long): 4 sizeof ( Long long): 8sizeof (M): 8 sizeof (N): 8 sizeof (X): 20 sizeof (Y): 20m.a:0 m.b:4 n.a:0 n.b:1 n.c:4 x.a:0 x.b.a:4 x.b.b:8 x.c:12// The x.c here do not have an address that is divisible by 8 Does the //system press 4 bytes? 32-bit system 8-byte alignment doesn't make sense? &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//32-bit system with 8 bytes of data in 8-byte alignment, memory read //is also read multiple times, wasting space on it to 8 bytes, and does not speed reading speed //because 32 is a system, the data bus is 32 bits, at a time can only fetch 4 //bytes of data, 8 bytes of data, aligned to 4 bytes and aligned to 8 bytes are the same // The hardware circuitry of the memory determines that the maximum is 4 byte aligned, and the alignment greater than 4 bytes isMeaningless y.a:0 y.b.a:4 y.b.b:5 y.b.c:8 y.c:12//here the y.c did not *//* to the address which divisible by 8 #pragma Pack (8) change to #pragma pack (1) program run Result: sizeof (char): 1 sizeof (short):2 sizeof (int): 4 sizeof (Long): 4 sizeof (Long long): 8sizeof (M): 5 sizeof (N): 6 sizeof ( X): 14 sizeof (Y): 15m.a:0 m.b:1 n.a:0 n.b:1 n.c:2 x.a:0 x.b.a:1 x.b.b:2 x.c:6y.a:0 y.b.a:1 y.b.b:2 y.b.c:3 y.c:7*//* put #pragma Pack (8) change to #pragma pack (4) program run Result: sizeof (char): 1 sizeof (short):2 sizeof (int): 4 sizeof (Long): 4 sizeof (Long long): 8sizeof (M): 8 sizeof (N): 8 sizeof ( X): 20 sizeof (Y): 20m.a:0 m.b:4 n.a:0 n.b:1 n.c:4 x.a:0 x.b.a:4 x.b.b:8 x.c:12y.a:0 y.b.a:4 y.b.b:5 y.b.c:8 y.c:12*/
This article is from the "11424402" blog, please be sure to keep this source http://11434402.blog.51cto.com/11424402/1761552
C-language structural body alignment