C语言结构体大小

吐血总结,在两次笔试题中都遇到,特总结如下:

P表示偏移量,D表示大小,sum为总大小;

规则1:P(i)能整除以D(i);

规则2:sum能整除以每个D(i);

规则3:sum=last_P(i)+last_D(I);总大小等于最后一个成员的偏移量加上最后一个成员的大小

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

struct stu2              8
          {
                int k;
                short t;
          }

struct stu3             12
          { 
                char c1; 
                int i;
                char c2;
          }
struct stu4                8
          {
                char c1;
                char c2;
                int i;
          }

如果结构体中的成员又是另外一种结构体类型时应该怎么计算呢?只需把其展开即可。但有一点需要注意,展开后的结构体的第一个成员的偏移量应当是被展开的结构体中最大的成员的整数倍。看下面的例子:
struct stu5                     16
                {
                short i;
                struct 
                {
                   char c;
                   int j;
                } ss; 
                int k;
          }
结构体stu5的成员ss.c的偏移量应该是4,而不是2。整个结构体大小应该是16。

C语言结构体大小_第1张图片

// Endian_1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include   
#include   
#include   
using namespace std; 

typedef struct node1
{
	int a[100];
	char b;
}sa;

typedef struct node2
{
	int a;
	char b;
}sb;
typedef struct node3
{
	int a;
	double b;
}sc;


typedef struct node4
{
	long long b; //long long是8B,long是4B
	char a;
}sd;

typedef struct node5
{
	unsigned short s1;///unsigned short 和short都是2B
	unsigned short s2;
}se;

typedef struct node6
{
	unsigned short s1;
	int i;  
	unsigned short s2;  
}sf;
typedef struct node7
{
	unsigned short s1;
	unsigned short s2;  
	int i;   ///

}sg;

typedef struct node8
{
	int i;
	char c;
	int j;

}sh;

struct stu5
{
	short i;
	struct 
	{
		char c;
		int j;
	} ss; 
	int k;
};


int _tmain(int argc, _TCHAR* argv[])
{
	cout<
环境:  win7  64,vs2010


你可能感兴趣的:(C/C++)