什么时候uintptr_t比intptr_t更受青睐? [英] When is uintptr_t preferred over intptr_t?

查看:78
本文介绍了什么时候uintptr_t比intptr_t更受青睐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我需要将通用"指针的值存储在结构中并且对指向的内存本身不感兴趣,我发现将其存储为intptr_t而不是将其存储为intptr_t在语义上更正确void*.问题是uintptr_t是否更合适,一般来说什么时候比另一个更受欢迎?

Given the requirement that I need to store the value of a "generic" pointer in a struct and have no interest in the pointed-at memory itself, I find it more semantically correct to store it as an intptr_t than a void*. The question is whether a uintptr_t is better suited or not, and when one is preferred over the other in general?

推荐答案

它主要是一个风格参数(优化的编译器可能会生成相同或非常相似的代码).但是,指针比较可能是一个棘手的问题.

It is mostly a stylistic argument (an optimizing compiler would probably generate the same, or very similar, code). However, pointer compares may be a tricky issue.

记住,纯标准C指针比较只对指向 same 聚合数据的指针有意义.可能不允许您比较的两个结果,例如保留排序的指针数组.

Remember than in purely standard C pointer compare is roughly meaningful only for pointers to the same aggregate data. You are probably not allowed to compare two results from malloc, e.g. to keep a sorted array of pointers.

我会将其保留为void*,否则保留为uintptr_t.带符号的intptr_t不能方便地隔离负数和正数,并且如果它们来自重要的应用程序指针,则可能不受欢迎.

I would keep them as void*, or else as uintptr_t. The signed intptr_t has the inconvenience to seggregate negative and positive numbers, and where they are coming from significant application pointers, this is probably not welcome.

请注意,不能取消引用void*:作为uintptr_t,您必须将其强制转换为对地址所指向的数据执行有用的操作;但是void*指针可以传递给memset

Notice that a void* cannot be dereferenced: as an uintptr_t, you have to cast it to do something useful with the data pointed by the address; however void* pointers can be passed to routines like memset

PS.我假设一个普通的处理器(例如某些x86,PowerPC,ARM等)具有平坦的虚拟地址空间.您可能会发现异国情调的处理器-也许有些DSP-差异非常大(也许intptr_t并不总是有意义的;请记住,在1990年代 C99 不存在,我不确定它的<stdint.h>在这样的计算机上是否有意义)

PS. I am assuming an ordinary processor (e.g. some x86, PowerPC, ARM, ...) with a flat virtual address space. You could find exotic processors -some DSPs perhaps- with very significant differences (and perhaps on which intptr_t is not always meaningful; remember that on the 1990s Cray Y-MP supercomputers sizeof(long*) != sizeof(char*); at that time C99 did not exist, and I am not sure its <stdint.h> could be meaningful on such machines)

这篇关于什么时候uintptr_t比intptr_t更受青睐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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