下图是从原文摘抄过来:
数据类型 | 16位编译器 | 32位编译器 | 64位编译器 |
---|---|---|---|
char | 1字节 | 1字节 | 1字节 |
char* | 2字节 | 4字节 | 8字节 |
short int | 2字节 | 2字节 | 2字节 |
int | 2字节 | 4字节 | 4字节 |
unsigned int | 2字节 | 4字节 | 4字节 |
float | 4字节 | 4字节 | 4字节 |
double | 8字节 | 8字节 | 8字节 |
long | 4字节 | 4字节 | 8字节 |
long long | 8字节 | 8字节 | 8字节 |
unsigned long | 4字节 | 4字节 | 8字节 |
#include <QApplication>
#include <iostream>
#include<stddef.h>
using namespace std;
#ifndef BYTE_8
#define BYTE_8 1
#endif
#ifndef BYTE_4
#define BYTE_4 1
#endif
#undef BYTE_8
#ifdef BYTE_4
#pragma pack(4)
#endif
#ifdef BYTE_8
#pragma pack(8)
#endif
typedef struct test_32
{
char a;
char d;
double c;
}test_32;
struct st1
{
char a ;
int b ;
short c ;
};
struct st2
{
short c ;
char a ;
int b ;
};
#ifdef BYTE_4
typedef struct Args
{
char ch; //1+3 = 4
double d; // 8
short st; //2
char rs[9]; //9+3 = 12
int i; //4 +4 +8 +12=28
} args;
typedef struct Argsa
{
char ch; //1+3 = 4;
Args test; //28
char jd[10]; //12
int i; //4 + 4+ 12 +28 = 48
}arga;
#endif
#ifdef BYTE_8
typedef struct Args
{
char ch; //1+7 = 8
double d; // 8
short st; //2
char rs[9]; //9+3 = 12
int i; //4 +8 +8 +12= 32
} args;
typedef struct Argsa
{
char ch; //1+7 = 8;
Args test; //32
char jd[10]; //10+2= 12
int i; //4 + 8+ 32 +12 = 56
}arga;
#endif
typedef struct __test_arr
{
char ch;
double dd;
char jd[9];
int i;
}test_arr;
#ifdef BYTE_4
typedef struct __ArgsP
{
int i; //4
double d; //8
char *p; //8 指针64位机器上默认8字节对齐,不管是否指定了4字节对齐规则
char ch; //4
int *pi; //8 +4 + 8 +8+4 = 32
}ArgsP;
#endif
#ifdef BYTE_8
typedef struct __ArgsP
{
int i; //8
double d; //8
char *p; //8 指针64位机器上默认8字节对齐
char ch; //8
int *pi; //8 指针64位机器上默认8字节对齐
}ArgsP;
#endif
struct m
{
int a;
short b;
int c;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
cout<<"sizeof(st1) -> "<<sizeof(st1)<<endl;
cout<<"sizeof(st2) -> "<<sizeof(st2)<<endl;
cout<<"sizeof(test_32) -> "<<sizeof(test_32)<<endl;
cout<<"Args:"<<sizeof(args)<<endl;
cout<<"test_arr:"<<sizeof(test_arr)<<endl;
cout<<"Argsa:"<<sizeof(arga)<<endl;
cout<<"ArgsP:"<<sizeof(ArgsP)<<endl;
cout <<"struct m size:"<< sizeof(m) << endl;
cout << endl;
int offset_b = offsetof(struct m, a);// 获得成员a相对于m储存地址的偏移量
int offset_b1 = offsetof(struct m, b);// 获得成员b相对于m储存地址的偏移量
int offset_b2 = offsetof(struct m, c);// 获得成员c相对于m储存地址的偏移量
cout <<"a offset relative to m storage address:"<< offset_b << endl;
cout << "b offset relative to m storage address:" << offset_b1 << endl;
cout << "c offset relative to m storage address:" << offset_b2 << endl;
return a.exec();
}
根据原作者写的,自己进行了一遍理解。