Use the simplest and most understandable method to calculate the size of a struct.

Struct size calculation must follow the byte alignment principle.

By default, struct byte alignment generally satisfies three rules:

  • 1) The first address of a struct variable must be divisible by the size of its widest fundamental type member;
  • 2) The offset of each member relative to the struct's first address is an integer multiple of the member's size; if necessary, the compiler adds padding bytes between members (internal adding);
  • 3) The total size of the struct is an integer multiple of the size of its widest fundamental type member; if necessary, the compiler adds padding bytes after the last member (trailing padding).

Actually, for the time being ignore these three rules. My method only requires remembering the third one: the struct size must be an integer multiple of the largest byte size among its members.

First look at the two structs defined below:

struct {   char a;   short b;   char c; }S1;

struct {  char  a;  char  b;  short c; }S2;

Respectively obtained by program testing:sizeof(S1)=6 , sizeof(S2)=4。

Note: Why does merely changing the order of struct members produce different results?

Solution:

  • (1) First find the largest byte size among the member variables. It can be seen that for S1 and S2, the largest is short, which occupies 2 bytes;
  • (2) Therefore, from now on, 2 bytes are used as the standard. That is to say, each member only needs at most 2 bytes, and the rest are filled as placeholders. Note that in the diagram below, one grid represents one byte;
  • (3) So first draw 2 grids, then look at the member order and increase step by step, with 2 as the increment basis each time.
For S1, the order ischar->short->char :

So for S1, the struct size is 2*3=6. As for why the second char's extra byte is not discarded, it follows the third rule: the struct size must be an integer multiple of the largest byte size among members.

S1=2*3=6

For S2, draw a diagram as well, but the order ischar->char->short:

S2=2*2=4

Using this method, look at another struct like this:

struct stu1
{
    int i;
    char c;
    int j;
};

Obviously, the largest byte size is 4. Order: int char int:

Because int occupies 4 bytes, and char already occupies 1, which is not enough, so those 3 bytes have to be extra placeholders.

Stu1=3*4=12

What if we change it?

struct stu2
{
    int i;
    int j;
    char  c;
};
Stu2=3*4=12

Look at another one: when a struct member variable is another struct, just add the member struct as a whole.

typedef struct A
{
    char a1;
    short int a2;
    int a3;
    double d;
};

A=16

typedef struct B
{
    long int b2;
    short int b1;
    A a;
};

For B, ignore A a first, that is, remove member A a and calculate struct B's size as 8, so the final result is 8+16=24; 24 is the final result.

Original address: https://www.cnblogs.com/lykbk/archive/2013/04/02/krtmbhrkhoirtj9468945.html