为-1有效的指针地址 [英] Is -1 a valid pointer address
问题描述
可能重复:结果
可以将指针(地址)永远是负面的?
我考虑初始化一个结构到所有-1s与memset的(因为它使用
无符号数和零是有效值)。
I'm considering initialising a structure to all -1s with memset(since it uses no signed numbers and zero is a valid value).
-1有效的指针ADRESS?以及是否有任何其他的问题,我的想法?
注:平台是Linux / GCC / 86
Is -1 a valid pointer adress? and are there any other problems with my idea? note: platform is linux/gcc/x86
P.S。我试图初始化结构,是不是所有的指针和其中零是有效的所有无效的数值一样,所以我可以选择做部分初始化功能于一体,并初始化非初始化字段以后默认值。如果有一个模式/策略在C这样做吗?
P.S. I'm trying to initialize a struct that is not all pointers and where zero is valid to all invalid like values so I can optionally do partial initialization in one function and initialise the non initialised fields to default values later on. If there is a pattern/strategy to do this in c?
推荐答案
的跨pretation -1
作为一个指针结构相关的,因此不可靠。
The interpretation of -1
as a pointer is architecture-dependent and therefore unreliable.
在一般情况下, memset的
用来设置字节,而不是指针。 C不作任何保证以字节个体如何结合起来,使一个指针。即使你的解决方案的工作,你就必须记录如何以及为什么它的工作原理。
In general, memset
is intended to set bytes, not pointers. C does not make any guarantees as to how individual bytes combine to make a pointer. Even if your solution works, you'll have to document how and why it works.
有一个更好的主意,当 NULL
是一个有效的值,是所有的指针设置为一个适当类型的定点。所以,如果你的结构有一个字段为int * IP
:
A better idea, when NULL
is a valid value, is to set all pointers to a sentinel of an appropriate type. So, if your structure has a field int *ip
:
static const int sentineli;
// in the initialization:
foo->ip = (int *)&sentineli;
则与该值进行比较。这是自文档。
then compare with that value. This is self-documenting.
这篇关于为-1有效的指针地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!