我學習C99和閱讀結構之後,我發現在Linux Kernel code下面的宏:Linux內核FIELD_SIZEOF宏解釋
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
我..什麼?用法:
#include <stdio.h>
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
struct book {
char title[100];
char author[100];
};
int main(void)
{
printf("%lu\n", FIELD_SIZEOF(struct book, title)); // prints 100
}
這裏的擴展器(gcc -E)
printf("%lu\n", (sizeof(((struct book*)0)->title)));
什麼我百思不得其解的是0
。我1
,2
,+1
,-1
,+999
和'a'
和"hello"
和它始終工作取而代之。
有沒有評論的來源。我知道->
用於通過指針訪問結構成員,但((struct book*)0)
怎樣才能成爲一個指針?宏如何工作?
它與標準的'offsetof'宏的常見實現類似,儘管這一點有點棘手。 –