Structure variable alignment

xiaoxiao2021-03-06  102

program:

#include #include

Typedef struct aa {int b; char A1; char A2; char A3; char A4; char A5; char A6; char A7; char A8; char A9; char A10; Double C; char D;};

/ ************************************************** ***********************************************************

I originally thought:

TypedEf struct aa {int b; 4 4 CHAR A1; 1 3 8 CHAR A2; 1 9 CHAR A3; 1 10 CHAR A4; 1 11 CHAR A5; 1 12 CHAR A6; 1 13 CHAR A7; 1 14 CHAR A8; 1 15 CHAR A9; 1 16 CHAR A10; 1 7 24 Double C; 8 32 Char D; 1 7 40};

But actually

in principle:

1. The variable in the structure is aligned.

2. Variable storage is in units of char, with the same type

Explanation:

A1 is char, b is int, and there is three air spaces behind A1.

However, A2, A3, A4 or the A1 is the same type, so it is still stored behind the A1

A5 ~ A10 total 6 char

But thereafter is a Double C, so supplement two spaces

Typedef struct aa {int b; 4 4 CHAR A1; 1 5 / * A1 To align, make three char, but thereafter, the variables are also char, and three char * / char A2; 1 6 char A3; 1 7 char A4; 1 8

Char A5; 1 9 CHAR A6; 1 10 Char A7; 1 11 Char A8; 1 12 CHAR A9; 1 13 CHAR A10; 1 2 16 / * Has already occupied 6 char, it is a Double, so supplement two char Air level * / double C; 8 24 char D; 1 7 32};

*********************************************************** *************************************************** /

INT main () {char DD = '/ 0'; AA AA; CHAR TT = '/ 0';

Char CC [100]; STRCPY (CC, "0123456789AbcDefghijklmnopqrStuvwxyz"); Memcpy (& AA, CC, SIZEOF (AA)); Printf ("SizeOf (AA) = [% D] / N", SIZEOF (AA));

Printf ("% S / N", (char *) & aa); Printf ("A1 =% C / N", AA.A1); Printf ("A2 =% C / N", AA.A2); Printf "A9 =% C / N", AA.A9); Printf ("A10 =% C / N", AA.A10); Printf ("D =% C / N", AA.D);

Return 0;}

Compile:

CC tt.cpp

result:

181: a.outsizeof (aa) = [32] 0123456789ABCDefghijklmnopQrstuva1 = 4A2 = 5A9 = CA10 = DD = O

转载请注明原文地址:https://www.9cbs.com/read-125935.html

New Post(0)