Easy Tutorial
❮ A Beginners Guide To Web Development Java Class Forname ❯

Calculating the Size of Structs

Category Programming Techniques

Calculating the size of structs in the simplest and most understandable way.

Struct size calculation must follow the byte alignment principle.

The default byte alignment for structs generally adheres to three guidelines:

>

For now, just focus on the third guideline, which states that the result of the struct size must be an integer multiple of the largest byte in the members.

Consider the following two struct definitions:

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

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

Testing with a program yields sizeof(S1)=6 , sizeof(S2)=4.

Note: Why does changing the order of struct members result in different sizes?

Explanation:

For S1, the struct size is 2*3=6. The extra byte for the second char is not discarded because it adheres to the third guideline, which states that the struct size must be an integer multiple of the largest byte in the members.

S1=2*3=6

For S2, draw a diagram with the order char->char->short:

S2=2*2=4

Using this method, consider this struct:

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

Clearly, the largest byte is 4. The order is int char int:

Since int occupies 4 bytes and char has already taken one, the remaining three bytes are used for padding.

Stu1=3*4=12

What if the order is changed?

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

Now, consider a struct where a member is another struct: Simply add the size of the nested 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, and calculate the size of struct B as 8. Therefore, the final result is 8+16=24; 24 is the final size.

>

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

#

-

** Song Song

* 105**[email protected]

The third guideline is incorrect, stating that "the result of the struct size must be an integer multiple of the largest byte in the members."

Correctly, if no alignment byte size is set, the largest member is the alignment byte size.

If an alignment byte size is set, the alignment byte size is: min(largest member, set alignment byte size).

Reference article: https://zhuanlan.zhihu.com/p/30007037

** Song Song

* 105**[email protected]

** Click to Share Notes

Cancel

-

-

-

❮ A Beginners Guide To Web Development Java Class Forname ❯