以下程序主要是为了证明两点:
1.内存对齐规则,可以自己设定对齐系数
2.只要两个结构体的成员变量数据类型及顺序一致,即使成员变量的名字不一样,通过类型转换后依然可以正确的读取到成员变量的值,因为类型转换时实际上是通过成员变量的大小进行对齐的,名字只是一个index而已。
#include <iostream>
#pragma pack(8) //设置对齐系数
using namespace std;
struct stu1 {
int a;
int b;
int c;
double d;
int e;
};
struct stu2{
double aa;
int b;
int c;
double d;
int e;
};
int main() {
stu1 s;
stu1* s1 = new stu1;
s1->a = 1;
s1->b = 2;
s1->c = 3;
s1->d = 4.01;
s1->e = 5;
cout << sizeof(s) << endl; //这样才能计算出结构体的实际大小
cout << sizeof(s1) << endl; //这样只能计算出指针的大小
cout << &(s1->a) << " " << s1->a << endl;
cout << &(s1->b) << " " << s1->b << endl;
cout << &(s1->c) << " " << s1->c << endl;
cout << &(s1->d) << " " << s1->d << endl;
cout << &(s1->e) << " " << s1->e << endl;
stu2* s2 = new stu2;
void* temp = s1;
s2 = (stu2*)temp;
cout << sizeof(s2) << endl;
cout << &(s2->aa) << " " << s2->aa << endl;
cout << &(s2->b) << " " << s2->b << endl;
cout << &(s2->c) << " " << s2->c << endl;
cout << &(s2->d) << " " << s2->d << endl;
cout << &(s2->e) << " " << s2->e << endl;
return 0;
}
|