sizeof的一点总结


=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=

char str[] = "hello";
sizeof(str) = 6;

void *p = malloc(100);
sizeof(p) = 4;

数组和指针的sizeof运算有着细微的区别:如果数组变量被传入函数中做sizeof运算,则和指针运算没有区别!

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=

struct S
{
   char c1;
   int i;
   char c2;
};
sizeof(S) = 12;

数位对齐规则:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=


class F
{
public:
	int a;
	static int b;
};

sizeof(F) = 4;
类静态成员的空间不再类的实例中,而是像全局变量一样在静态存储区中,被类共享


=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=
char str1[20] = "0123456789";
strlen(str1) = 10;
sizeof(str1) = 20;

strlen sizeof 的计算数组名大小方式

数组做参数传递给函数退化成指针,此时strlen() 仍为实际大小,sizeof()则是指针大小 = 4;
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=

#pragma pack(2)

union u
{
	char buf[9];
	int a;
};

sizeof(u) = 10;

通过#pragma pack手动更改对齐方式为2个字节;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章