//code from linux 0.11
linux/include/stddef.h里有个宏定义:
ps:
对于结构体:
offsetof(struct aa,a) == 0
offsetof(struct aa,b) == 8
offsetof(struct aa,c) == 9
可MinGW Developer Studio下测试时,
offsetof(struct aa,a) == 0
offsetof(struct aa,b) == 8
offsetof(struct aa,c) == 12 /* 不解!! */
附测试程序:
linux/include/stddef.h里有个宏定义:
#define offsetof(TYPE,MEMBER) ((size_t)&)(TYPE *)0) -> MEMBER)
它 的作用是计算某一成员在结构类型中的偏移位置。使用这个宏可以确定一个成员(字段)在包含它的结构类型中从类型开始处算起的字节偏移量。宏的结果是 size_t的整数常数表达式。((CTYPE *)0)是将一个整数0类型投射(typecast)成数据对象指针类型,然后在该结果上进行运算。
ps:
- typedef unsigned long size_t;
struct aa
{
long long a;
char b;
int c;
}t;
理论上计算得:
offsetof(struct aa,a) == 0
offsetof(struct aa,b) == 8
offsetof(struct aa,c) == 9
可MinGW Developer Studio下测试时,
offsetof(struct aa,a) == 0
offsetof(struct aa,b) == 8
offsetof(struct aa,c) == 12 /* 不解!! */
附测试程序:
- /* 2008.10.12 */
- #include<stddef.h>
- #include<stdio.h>
- int main()
- {
- struct aa
- {
- long long a;
- char b;
- int c;
- }t;
- unsigned long a1;
- a1 = offsetof(struct aa,a);
- //a1 = ((unsigned long) & ((struct aa *)0) -> a);
- printf("aa-a:%ld/n",a1);
- a1 = ((unsigned long) & ((struct aa *)0) -> b);
- printf("aa-b:%ld/n",a1);
- a1 = ((unsigned long) & ((struct aa *)0) -> c);
- printf("aa-c:%ld/n",a1);
- printf("sizeof(char) -- %d/n",sizeof(char));
- printf("sizeof(int) -- %d/n",sizeof(int));
- printf("sizeof(long) -- %d/n",sizeof(long));
- printf("sizeof(long long) -- %d/n",sizeof(long long));
- return 0;
- }