针对32位系统和64为系统下sizeof()的大小,包括指针的长度

长度 32位系统 64位系统
指针 4字节 8字节
int 4 8
char 1 1
double 8 16

情形一:

#include"stdafx.h"
#include
#include
#include

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

using namespace std;

struct a {

	int d;//4byte
	double aaa;//8byte
	short b;//2byte
	char c; //1byte
}aa;
int main() {
	cout << sizeof(aa)<

经过测试发现,我自己的编译环境好像是32位的,所以int长度为4,它每次生成最大的空间,然后类似于填背包的形式,把小的的塞入大的里面存放,当剩余的内存不足以存放下一个类型的大小时才会开新的最大长度的空间。

 

注意sizeof(指针),这种情况比较特殊,例如如下情况

#include"stdafx.h"
#include

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;
}

针对32位系统和64为系统下sizeof()的大小,包括指针的长度_第1张图片

 

如果是对sizeof(type_double),求得是指针地址的长度,该长度是固定的不管是int还是double,都是4,测试环境应该是32位,

如果是sizeof(*type_xxx),相当于sizeof(int),长度为指针a指向的类型的长度,int为4位,double为8位,测试环境应该是32位。

 

情形三:有数组的情况下:

#include"stdafx.h"
#include

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;
}

三种结果如下:

针对32位系统和64为系统下sizeof()的大小,包括指针的长度_第2张图片

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