标签:大小端存储
A的ASCII码16进制存储为41,对应B,C,D,E为42,43,44,45;
VS下为小段模式
将高精度存入低精度时,截取掉高位,高位补ff,内存中默认用cc初始化
3.
#include<stddef.h>
#pragma pack(4)
struct A
{
int a;
char b;
short c;
char d[11];
};
aaaab0cc
dddddddd
ddd//应补齐最大对齐数的整数倍
int main()
{
cout << sizeof(A) << endl;
cout << offsetof(A,a) << offsetof(A,b) << offsetof(A,c) << offsetof(A,d) << endl;
system("pause");
return 0;
}运行结果为:20 0,4,6,8
4.
struct B
{
int a;
char c;
double d;
};
//aaaac000
//dddddddd
cout << sizeof(B) << endl;
cout << offsetof(B,a) << offsetof(B,c) << offsetof(B,d) << endl;运行结果:16 0,4,8
5.
struct A
{
int a;
char b;
short c;
char d[11];
};
struct B
{
int a;
char c;
double d;
A e;
};
cout << sizeof(B) << endl;
cout << offsetof(B, a) << offsetof(B, c) << offsetof(B, d) << offsetof(B, e) << endl;运行结果:36 0,4,8,16
e不是对齐到d后面,按A本身最大整数倍对齐数。
6.
#include<stddef.h>
#pragma pack(4)
struct A
{
int a;
char b;
short c;
char d[11];
};
struct B
{
int a;
double d;
char c;
A e;
};
cout << sizeof(B) << endl;
cout << offsetof(B, a) << offsetof(B, c) << offsetof(B, d) << offsetof(B, e) << endl;运行结果:36 0,4,12,16
7.
#include<stddef.h>
#pragma pack(8)
struct A
{
int a;
char b;
short c;
char d[11];
};
struct B
{
int a;
double d;
char c;
A e;
};
cout << sizeof(B) << endl;
cout << offsetof(B, a) << offsetof(B, c) << offsetof(B, d) << offsetof(B, e) << endl;运行结果:40 0,8,16,20
总结:
结构体中第一个变量地址等于结构体起始地址
第一个变量永远对齐到0偏移(相对于结构体的起始位置),永远对齐(结构体中最大对齐数整数倍)-----结构体大小。
对齐数:结构体中最大的和系统中的较小者。windows:8,Linux:4
本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1767609
标签:大小端存储
原文地址:http://10541556.blog.51cto.com/10531556/1767609