长度 | 32位系统 | 64位系统 |
指针 | 4字节 | 8字节 |
int | 4 | 8 |
char | 1 | 1 |
double | 8 | 16 |
情形一:
#include"stdafx.h"
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
struct a {
double aaa;//8byte
int d; //4byte
short b; //2byte
char c; //1byte
}aa;
int main() {
aa={ 3,4,1,'a' };
cout << sizeof(aa);
return 0;
}
情形二:
#include"stdafx.h"
#include<iostream>
using namespace std;
struct a {
int d;//4byte
double aaa;//8byte
short b;//2byte
char c; //1byte
}aa;
int main() {
cout << sizeof(aa)<<endl;
return 0;
}
经过测试发现,我自己的编译环境好像是32位的,所以int长度为4,它每次生成最大的空间,然后类似于填背包的形式,把小的的塞入大的里面存放,当剩余的内存不足以存放下一个类型的大小时才会开新的最大长度的空间。
注意sizeof(指针),这种情况比较特殊,例如如下情况
#include"stdafx.h"
#include<iostream>
using namespace std;
int main() {
double *type_double = new double;
int *type_int = new int;
printf("地址=%p\n", type_double);
cout << "sizeof(type_double)=" << sizeof(type_double) << endl;
cout << "sizeof(*type_double)=" << sizeof(*type_double) << endl;
cout << "sizeof(type_int)=" << sizeof(type_int) << endl;
cout << "sizeof(*type_int)=" << sizeof(*type_int) << endl;
}
如果是对sizeof(type_double),求得是指针地址的长度,该长度是固定的不管是int还是double,都是4,测试环境应该是32位,
如果是sizeof(*type_xxx),相当于sizeof(int),长度为指针a指向的类型的长度,int为4位,double为8位,测试环境应该是32位。
情形三:有数组的情况下:
#include"stdafx.h"
#include<iostream>
using namespace std;
typedef struct a {
double aaa;//8byte
char c[0]; //1byte 三种不同长度数组
//char c[5];
//char c[9];
}m;
int main()
cout << sizeof(m) << endl;
return 0;
}
三种结果如下: