Linux内核FIELD_SIZEOF宏观的说明 [英] Explanation of Linux Kernel FIELD_SIZEOF macro

查看:873
本文介绍了Linux内核FIELD_SIZEOF宏观的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C99和阅读结构后,我发现在的 Linux内核code

I'm learning c99 and after reading about structures I found the following macro in the Linux Kernel code:

#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))

我..什么?用法:

I.. what? Usage:

#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)

Here's the expansion (gcc -E)

printf("%lu\n", (sizeof(((struct book*)0)->title)));

什么我百思不得其解的是 0 。我与 1 替换它, 2 +1 1 +999 'A'你好它总是工作原理

What really baffles me is the 0. I replaced it with 1, 2, +1, -1, +999 and 'a' and "hello", and it always works.

有源无可奉告。我知道, - &GT; 用于通过指针访问结构成员,但怎么能((结构本书*)0)是一个指针?如何在宏工作?

There's no comment in the source. I know that -> is used to access a struct member through a pointer, but how can ((struct book*)0) be a pointer? How does the macro work?

推荐答案

这里的关键是,的sizeof 是在编译时编译器计算。因此,您所指定的指针从来没有真正取消引用。毕竟,在物体处于不会改变它的大小。在的sizeof 运营商将在类型方面完全评估其操作数。

The key here is that sizeof is calculated by the compiler at compile time. So, the pointer you specify is never actually dereferenced. After all, where an object is located won't change its size. The sizeof operator will evaluate its operand purely in terms of types.

所以,你使用的地址实际上是无关紧要的,但 0 NULL )是一种常见的选择。

So, the address you use is actually irrelevant, but 0 (NULL) is a common choice.

这篇关于Linux内核FIELD_SIZEOF宏观的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆