sizeof , offsetof
1.sizeof是c/c++中的一个操作符(operator),返回一个对象或者类型所占的内存字节数
(1)使用:用于数据类型,变量
(2)判断 类型在本机的大小,计算数组中元素的个数
2.offsetof : offset of a structure member
头文件: #include<stddef.h>
size_t offsetof(type,member);
the macro offsetof() returns the offset of the field member from the start of the
structure type.
类似的可以仿写一个
#define offsetof(type,f) ((size_t) \ ( (char *) &((type *)0)->f - (char*)(type*)0) )
解释:(type*)0 假设将type类型放在0x00000000处,(type*)0->f 指向了f在0x00000000
处的偏移位置,相对位置-起始位置=相对偏移位置,于是就得出了 f在 type类型中的偏移量
linux programmer's Manual 中一个例子
#include<stddef.h> #include<stdio.h> #include<stdlib.h> int main(void) { struct s{ int i; char c; double d; char a[]; }; printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n", (long) offsetof(struct s, i), (long) offsetof(struct s, c), (long) offsetof(struct s, d), (long) offsetof(struct s, a)); printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s)); return 0; } result : offsets: i=0; c=4; d=8; a=16 sizeof(struct s)=16