一个指针(地址)都不能是负数? [英] Can a pointer (address) ever be negative?

查看:190
本文介绍了一个指针(地址)都不能是负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我希望能为返回特殊值的函数的失败的和的未初始化的(它成功返回一个指针)。

I have a function that I would like to be able to return special values for failure and uninitialized (it returns a pointer on success).

目前返回的 NULL 失败,和 1 作为初始化,这似乎工作...但我可以欺骗系统。 IIRC,地址总是积极的,不是吗? (虽然因为编译器是让我一个地址设置为-1,这似乎很奇怪)。

Currently it returns NULL for failure, and -1 for uninitialized, and this seems to work...but I could be cheating the system. iirc, addresses are always positive, are they not? (although since the compiler is allowing me to set an address to -1, this seems strange).

[更新]
另一个想法我(在事件-1是危险的),是到malloc的字符@全球范围内,并使用该地址作为定点。

[update] Another idea I had (in the event that -1 was risky) is to malloc a char @ the global scope, and use that address as a sentinel.

推荐答案

没有,地址并不总是积极的 - 在x86_64,指针是符号扩展和地址空间是围绕0对称集群(虽然它是平常的负面的地址是内核地址)。

No, addresses aren't always positive - on x86_64, pointers are sign-extended and the address space is clustered symmetrically around 0 (though it is usual for the "negative" addresses to be kernel addresses).

不过该点主要是没有实际意义,因为C语言只定义了&LT的含义; > 指针比较属于同一个对象,或者一个过去的阵列的端的部分指针之间。指针完全不同的对象不能进行有意义的比较比精确平等,至少在标准C其他 - 如果(P< NULL)。还没有明确的语义

However the point is mostly moot, since C only defines the meaning of < and > pointer comparisons between pointers that are to part of the same object, or one past the end of an array. Pointers to completely different objects cannot be meaningfully compared other than for exact equality, at least in standard C - if (p < NULL) has no well defined semantics.

您应该创建具有静态存储持续时间的虚拟对象,并使用其地址作为你的 unintialised 值:

You should create a dummy object with static storage duration and use its address as your unintialised value:

extern char uninit_sentinel;
#define UNINITIALISED ((void *)&uninit_sentinel)

这是保证整个程序有一个单一的,唯一的地址。

It's guaranteed to have a single, unique address across your program.

这篇关于一个指针(地址)都不能是负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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