首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

#define offsetof(type, f) ((size_t) \ ((char *)&((type *)0)->f - (char *)

2012-02-20 
#define offsetof(type, f) ((size_t) \ ((char *)&((type *)0)-f - (char *)(type *)0))谁能解释一下#de

#define offsetof(type, f) ((size_t) \ ((char *)&((type *)0)->f - (char *)(type *)0))谁能解释一下
#define   offsetof(type,   f)   ((size_t)   \
((char   *)&((type   *)0)-> f   -   (char   *)(type   *)0))

[解决办法]
先将0转化为 type*类型的指针,然后取得成员变量的地址,在减去0
最后得到的就是 成员变量的偏移地址.
[解决办法]
http://c-faq-chn.sourceforge.net/ccfaq/node30.html
我在上面网页中找到的这个解释,你看是不是正确:
3.12 如何确定域在结构中的字节偏移?
ANSI C在 <stddef.h> 中定义了offsetof() 宏, 用 offsetof(struct s, f) 可以计算出域 f 在结构 s 中的偏移量。 如果出于某种原因, 你需要自己实现这个功能, 可以使用下边这样的代码:
#define offsetof(type, f) ((size_t) \
((char *)&((type *)0)-> f - (char *)(type *)0))

这种实现不是 100% 的可移植; 某些编译器可能会合法地拒绝接受。


[解决办法]
#define offsetof(type, f) ((size_t) \
((char *)&((type *)0)-> f - (char *)(type *)0))

type为class或struct类型名,f为type类型成员。现在要确定f在type对象模型中的空间位置,很自然地想到将一个type类型对象起始地址设为0,再计算出f的起始地址,二者之差即为f在type中的位置:
type类型对象:(type *)0
对象起始地址:(char *)&((type *)0),char *是为了保证字节为单位,只要你不试图去改变它,这样是合法的
f的起始地址:((char *)&((type *)0)-> f
[解决办法]
#define offsetof(type, f) ((size_t)((char *)&((type *)0)-> f - (char *)(type *)0))

宏定义是:求得成员f在type变量中的偏移量

给你个调用实例

struct list{
char ch;
int num;
int f;
}demo;

size_t offset = offsetof(demo, f);

上面说的也不错

[解决办法]
struct type
{
int x;
int f;
};
type* p=(type *)0;
printf( "%d ",&(p-> f));
这样能理解了么?

热点排行