不(为size_t)((的char *)0)以往任何时候都不能计算为0? [英] Does (size_t)((char *)0) ever not evaluate to 0?

查看:145
本文介绍了不(为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.

如果有一个编译器或场景,其中(为size_t)((的char *)0)!= 0 ,是什么呢?

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

推荐答案

好了,你也知道,给定类型的空指针的物理重新presentation不一定全零的位模式。当强制转换指针(任何指针)的值为整型,其结果是所定义的实施,但通常(并且是这样的意图)的指针的数值 - 数字地址 - 保持不变,如果可能的话。这意味着,如果在给定的平台类型的空指针的char * 重新由 0xBAADF00D psented $ P $格局(例如),上述前pression将评估为 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).

此外,作为额外的音符,不同类型的空指针值可以具有不同的物理重新presentations,这意味着在理论上可以从获得不同的值(为size_t)(为(int *) 0)(为size_t)((的char *)0)(为size_t)((双*)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.

P.S。阅读这里(C FAQ)与非零空指针的实际平台的一些例子。

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天全站免登陆