时间:2011年9月20号 23:30
目的:对 sizeof 做一个总结
心得:阅历、本质、理解
-------------------------------------------------------------------------华丽的分割线--------------------------------------------------------------------
(一)首先要明确一个概念:sizeof是一个运算符而不是一个函数,它计算所占内存的大小
(二)两种用法
1、类型 sizeof(类型) 必须要有括号
2、变量 sizeof 变量 或sizeof(变量)
注意:sizeof操作符不能用于函数类型,不完全类型或位字段。不完全类型指具有未知存储大小的数据类型,如未知存储大小的数组类型、未知内容的结构或 联合类型、void 类型等。
(三)所得到的结果
Sizeof (类型) 得到的是类型所占的内存空间大小
Sizeof(指针或地址) 根据你是32位机还是64位机来确定 (32位为4,64位为8)
Sizeof(结构体或类) 根据字节对齐来确定结果 (之前有总结字节对齐的问题)
附:
原来有段时间个人对sizeof(数组名)和sizeof(&数组名)的结果纠结过
现在来对这个问题给出解释:
首先解释下数组名
(1)数组名一种数据结构,这种数据结构就是数组。
(2)数组名可以转换为指向其所指向实体的指针,即作为函数参数的时候
(3)数组名是不能进行加减的。
所以sizeof(数组名) 的结果 当然是数组所占的空间的大小
Sizeof(& 数组名 ) 的结果 是 4 ( 32 位机) vc6.0上有错误和编译器的实现有关当然int a[10]; a+1和&a+1的意义是完全不一样的 a表示的是数组的首地址而 &a 则表示数组首元素的首地址
当sizeof(数组)时注意动态数组 c89不支持动态数组但c99支持
(四)Sizeof是运算符所以是在预处理的时候实现的,即根据编译器的规定来决定计算的
一直很想看实现源码但没找到
在网上找到一个用宏来实现但感觉这个方法不完全对(某些情况不适用)
#define SIZEOF(x) ((char*)(&x+1)-(char*)&x)
int a[sizeof(int)] //正确
int a[SIZEOF(b)];(b为int的变量)//错误 等……
(五)MSDN上的定义
sizeof Operator
sizeof expression
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type
(including aggregate types). This keyword returns a value of type size_t.
The expression is either an identifier or a type-cast expression (a type specifier enclosed in
parentheses).
When applied to a structure type or variable, sizeof returns the actual size, which may include
padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof
returns the size of the entire array. The sizeof operator cannot return the size of dynamically
allocated arrays or external arrays.