- 论坛徽章:
- 0
|
//code from linux 0.11
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) == 0offsetof(struct aa,b) == 8offsetof(struct aa,c) == 9
可MinGW Developer Studio下测试时,
offsetof(struct aa,a) == 0offsetof(struct aa,b) == 8offsetof(struct aa,c) == 12 /* 不解!! */
附测试程序:
/* 2008.10.12 */
#includestddef.h>
#includestdio.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;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/33029/showart_1286738.html |
|