为什么这个实施offsetof()的工作? [英] Why does this implementation of offsetof() work?

查看:161
本文介绍了为什么这个实施offsetof()的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ANSI C,offsetof的定义如下。

In ANSI C, offsetof is defined as below.

#define offsetof(st, m) \
    ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))

为什么不抛出这样一个分割的错,因为我们提领一空指针?或者,这是某种形式的黑客编译的地方看到,只有地址取出来,所以静态计算,而无需实际提领它地址的偏移量?也就是这个code便携式?

Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?

推荐答案

在上述code无点是什么,取消引用。 使用上的地址值来查找参考价值;&GT - 当 * 发生反引用。唯一使用的* 上面是一个类型声明铸造的目的。

At no point in the above code is anything dereferenced. A dereference occurs when the * or -> is used on an address value to find referenced value. The only use of * above is in a type declaration for the purpose of casting.

- > 运算符上面使用,但它不是用来访问值。相反,它被用来抢值的地址。这里是一个非宏code样品应该使它更清楚一点。

The -> operator is used above but it's not used to access the value. Instead it's used to grab the address of the value. Here is a non-macro code sample that should make it a bit clearer

SomeType *pSomeType = GetTheValue();
int* pMember = &(pSomeType->SomeIntMember);

第二行实际上并没有引起反引用(取决于具体实现)。它简单地返回 SomeIntMember pSomeType 值范围内的地址。

你看到的是很多任意类型和字符指针之间的铸造。原因CHAR是,它是唯一的类型(也许是唯一的)键入它有一个明确的尺寸C89标准之一。大小1.确保大小是一个,上面的code可以做计算的真正价值偏移的煞魔。

What you see is a lot of casting between arbitrary types and char pointers. The reason for char is that it's one of the only type (perhaps the only) type in the C89 standard which has an explicit size. The size is 1. By ensuring the size is one, the above code can do the evil magic of calculating the true offset of the value.

这篇关于为什么这个实施offsetof()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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