How to calculate the size of a structure in C language

Due to the problem of address alignment of storage variables, there are 3 rules for calculating the size of the structure:

  1. The size of the structure is composed of n size modules of "the largest type in the structure" (n<=number of members);
  2. In a module, multiple members can be stored, provided that the size of the multiple members does not exceed the storage size of the module;
  3. Members of a structure are stored in the order they are defined.

The following example illustrates that we can use sizeof() to calculate the size.

sizeof(char)   = 1
sizeof(short)  = 2
sizeof(int)    = 4
sizeof(long)   = 4
sizeof(float)  = 4
sizeof(double) = 8

Example 1:

struct Str1
{
    
    
	char a;
	char b;
} str1;

struct Str1 str1;//sizeof(str1) = 2

insert image description here
The maximum member size in the structure is sizeof(char) = 1, so the size of str1 is 1+1 = 2;

Example 2:

struct Str2
{
    
    
	char a;
	char b;
	int c;
} str2;

struct Str2 str2;//sizeof(str2) = 8

insert image description here

The largest member size in the structure is sizeof(int) = 4, stored in order, so the size of str2 is 4+4 = 8;

Example 3:

struct Str3
{
    
    
	char a;
	int c;
	char b;
} str3;

struct Str3 str3;//sizeof(str3) = 12

insert image description here
The largest member size in the structure is sizeof(int) = 4, stored in order, so the size of str3 is 4+4+4 = 12;

Example 4:

struct Str4
{
    
    
	char a;
	char b;
	int c;
	double d;
} str4;

struct Str4 str4;//sizeof(str4) = 16

insert image description here
The largest member size in the structure is sizeof(double) = 8, stored in order, so the size of str4 is 8+8 = 16;

Example 5:

struct Str5
{
    
    
	char a;
	double f;
	char b;
	int c;
	double d;
} str5;

struct Str5 str5;//sizeof(str5) = 32

insert image description here
The largest member size in the structure is sizeof(double) = 8, stored in order, so the size of str5 is 8+8+8+8 = 32;

Reference: https://blog.csdn.net/Surge_Pitt/article/details/109577614

Guess you like

Origin blog.csdn.net/qq_44678607/article/details/130506639