C语言关键字之sizeof
C语言关键字 sizeof 是一个操作符,返回对象或类型所占内存字节数,类型为size_t(定义在<stddef.h>),有2种用法:
- sizeof unary-expression
- sizeof (type-name)
sizeof不能应用的场合:
- an expression that has function type or an incomplete type
- the parenthesized name of such a type
- an expression that designates a bit-field member
如果操作数的类型是VLA (variable length array),要进行evaluate;否则不需要evaluate,结果是一个整形常量。
示例1 进程间通信 比如storage allocator 和 I/O system
extern void *alloc(size_t); double *dp = alloc(sizeof *dp);
示例2 计算数组中元素个数
sizeof array / sizeof array[0]
示例3 VLA大小计算
#include <stddef.h> size_t fsize3(int n) { char b[n+3]; // variable length array return sizeof b; // execution time sizeof } int main() { size_t size; size = fsize3(10); // fsize3 returns 13 return 0; }
ANSI C规定字符型1字节,其余sizeof的返回结果与编译器实现相关。在32位系统中:
1. 基本类型
_Bool 1
char 1
short 2
int 4
long 4
long long 8
float 4
double 8
long double 12
_Complex 16
void 1
2. 指针
4
3. 枚举
4
4. 数组
数组长度 * 数组成员size
5. 结构体
字节对齐值:ALIGN
基本类型成员:SIZE
每个成员相对于结构体首地址的偏移都是min(ALIGN, SIZE)的整数倍,可能在成员间加填充字节
结构体总大小为min(ALIGN, SIZEmax)的整数倍,可能在最后一个成员后加填充字节
6. 联合
规则类似struct
测试程序:
#include <stdio.h> #include <complex.h> #define SIZEOF(x) printf("size of '%s' is %zd\n", #x, sizeof(x)); int main() { SIZEOF(_Bool); SIZEOF(char); SIZEOF(short); SIZEOF(int); SIZEOF(long); SIZEOF(long long); SIZEOF(float); SIZEOF(double); SIZEOF(long double); // depends on -m128bit-long-double SIZEOF(_Complex); SIZEOF(void); SIZEOF(void*); SIZEOF(void (*)(void)); // function pointer SIZEOF(enum {E}); SIZEOF(char [0]); // zero-size array SIZEOF(int [3]); SIZEOF(struct {}); // empty struct SIZEOF(struct {char c;}); SIZEOF(struct {char c; short s;}); // alignment SIZEOF(struct {int i; char c;}); SIZEOF(struct {int i; char c;} __attribute__((packed))); #pragma pack(push) #pragma pack(1) printf("With #pragma pack(1): "); SIZEOF(struct {int i; char c;}); #pragma pack(pop) SIZEOF(struct {double d; char c;}); // depends on -malign-double SIZEOF(struct {char c1:4; char :2; char c2:2;}); // bit field SIZEOF(struct {int i:1; char c:2;}); SIZEOF(struct {struct {int i; char c;}; short s;}); SIZEOF(struct {struct {short s1; char c;}; short s2;}); SIZEOF(struct {char c2; struct {short s1; char c1;}; short s2;}); SIZEOF(union {char c; int i;}); // union return 0; }