(size_t)((char *)0)不会计算为0吗? [英] Does (size_t)((char *)0) ever not evaluate to 0?

查看:125
本文介绍了(size_t)((char *)0)不会计算为0吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据为什么要在offsetof()中减去空指针中的响应?(和我对K& R的读取),C标准不要求(size_t)((char *)0)== 0 。但是,我从来没有见过将一个空指针转换为整数类型的方法可以计算任何其他值。

According to the responses in "Why subtract null pointer in offsetof()?" (and my reading of K&R), the C standard doesn't require that (size_t)((char *)0) == 0. Still, I've never seen a situation where casting a null pointer to an integer type evaluates to anything else.

如果有一个编译器或场景<$ c $

If there is a compiler or scenario where (size_t)((char *)0) != 0, what is it?

推荐答案

p>好吧,你知道,给定类型的空指针的物理表示不一定是全零位模式。当强制将指针(任何指针)值转换为整数类型时,结果是实现定义的,但是通常(并且这是意图),如果可能,指针的数值 - 数字地址 - 保持不变。这意味着如果在给定平台上, char * 的空指针由 0xBAADF00D pattern(例如) ,上面的表达式将求值为 0xBAADF00D ,而不是零。当然,你需要一个具有非零空指针的平台。我个人从来没有使用这样的平台,虽然我听说过一些真正的平台,像这样(在嵌入式平台的领域,这是不寻常的)。

Well, as you know, the physical representation of null pointer of a given type is not necessarily all-zero bit pattern. When you forcefully convert a pointer (any pointer) value to integer type, the result is implementation defined, but normally (and that's the intent) the numerical value of the pointer - the numerical address - remains unchanged, if possible. This means that if on a given platform a null pointer of type char * is represented by 0xBAADF00D pattern (for example), the above expression will evaluate to 0xBAADF00D, and not to zero. Of course, for that you'd need a platform with non-zero null-pointers. I personally never worked with such platforms, although I heard about a number of real platforms like that out there (like, in the realm of embedded platforms it is not something unusual).

此外,作为附加注释,不同类型的空指针值可以具有不同的物理表示,这意味着理论上可以从(size_t)((int *)0)(size_t)((char *)0)(size_t)(double *)0)。但这将是一个相当奇怪的情况,尽管从抽象C语言的角度来看是完全可能的。

Moreover, as an additional note, null pointer values of different types can have different physical representations, meaning that in theory you can get different values from (size_t) ((int *) 0), (size_t) ((char *) 0) and (size_t) ((double *) 0). But that would be a rather exotic situation, albeit perfectly possible from the point of view of abstract C language.

有关具有非零空指针的实际平台的一些示例,请参阅此处(C常见问题解答) 。

P.S. Read here (C FAQ) for some examples of actual platforms with non-zero null pointers.

这篇关于(size_t)((char *)0)不会计算为0吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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