offset 巨集

2010-05-21 5:34 pm
最近在看linux的code時,有發現一個offset巨集,雖然知道它是做什麼的並且執行後的結果也知道。
但是我還是不懂他這麼寫的方式是為什麼?如下
#define FIELD_OFFSET(type, field)((unsigned long)(long *)&(((type *)0)->field))
#define _OFFSET(field)((int)FIELD_OFFSET(APMIB_T,field))

請問是否有哪位高手可以幫忙解惑ㄧ下,或是能給我ㄧ些參考資料,感激不盡。
更新1:

TO David : 當然可以啦

回答 (1)

2010-05-22 1:03 am
✔ 最佳答案
Can I answer this in English?

2010-05-21 17:03:19 補充:
The other user has more or less answered this. The following is an example of how this works:
#define FIELD_OFFSET(type, field)((unsigned long)(long *)&(((type *)0)->field))

typedef struct test_struct {
int i;
char ch;
float fl;
} s;

main()
{
s test;

test.i = 10;
test.ch = 'c';
test.fl = 9.9;

printf("%x\n", FIELD_OFFSET( s, fl ));
}

The preprocessor will turn the line with the macro to:
printf("%x\n", ((unsigned long)(long *)&((( s *)0)-> fl )) );

Note that the pointer to 0 seems to be invalid. However, this will not be translated to any code by the compiler. This is address calculation and will be done by the compiler and translated to a number instead during compile-time.

So, this line means to print the address of the location of the field fl of a structure of typedef s of which has a starting location of 0 after casting it to an unsigned long. Since the starting location is address 0, the outcome will be the offset from the beginning of the structure.

So, assuming you can actually have a structure at location 0 by (s *) 0, then &(s*0)->fl is the address of the field fl within the structure s. Since this structure starts at 0, the address of fl is the offset of fl.


收錄日期: 2021-04-30 13:01:58
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20100521000010KK01647

檢視 Wayback Machine 備份