C语言关键字之sizeof

C语言关键字 sizeof 是一个操作符,返回对象或类型所占内存字节数,类型为size_t(定义在<stddef.h>),有2种用法:

sizeof unary-expressionsizeof (type-name)

sizeof不能应用的场合:

如果操作数的类型是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 }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( SIZEOF(_Complex);SIZEOF(void);SIZEOF(void*);SIZEOF(void (*)(void)); // function pointerSIZEOF(enum {E});SIZEOF(char [0]); // zero-size arraySIZEOF(int [3]);SIZEOF(struct {}); // empty structSIZEOF(struct {char c;});SIZEOF(struct {char c; short s;}); // alignmentSIZEOF(struct {int i; char c;});SIZEOF(struct {int i; char c;} __attribute__((packed)));#pragma pack(push)#pragma pack(1)printf();SIZEOF(struct {int i; char c;});#pragma pack(pop)SIZEOF(struct {double d; char c;}); // depends on -malign-doubleSIZEOF(struct {char c1:4; char :2; char c2:2;}); // bit fieldSIZEOF(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 {;}

第一个青春是上帝给的;第二个的青春是靠自己努力的

C语言关键字之sizeof

相关文章:

你感兴趣的文章:

标签云: