通过阅读与 size_t
和 ptrdiff_t
相关的在线帖子,我想确认以下几点:
如果数组的最大大小小于
1/2*(max number represent-able by size_t)
,我可以安全地使用ptrdiff_t
并且检查指向同一个对象的两个指针之间的相对距离?(因为我说的是数组,所以“指向同一个对象的指针”是指“指向同一个数组的指针”)。如果我想声明一个可以表示与另一个指针的偏移量的变量,我最好将其声明为类型
ptrdiff_t
?如何在 C 和 C++ 中输出
size_t
和ptrdiff_t
类型的变量?以下是否正确:Cross platform format string for variables of type size_t?is
uintptr_t
只是size_t
的另一个名称,或者它应该用作size_t
的单独类型?是
ssize_t
和intptr_t
的另一个名称ptrdiff_t
还是必须以不同的方式使用?
我开始在 Ubuntu 上使用 gcc。我刚刚在使用某人时发现了这些类型 else 的代码。
添加:我确实希望能够使用 negative 偏移量。以及使用 uintptr_t
和 intptr_t
有什么区别?
最佳答案
1: if the max size of an array is less than 1/2*(max number represent-able by
size_t
), I can safely useptrdiff_t
and check the relative distances between two pointers to the same object?
如果 sizeof(size_t) <= sizeof(prtdiff_t)
.在合理的实现中会出现这种情况,但不能保证。
2: if I want to declare a variable that can represent the offset from another pointer, I better declare it as type
ptrdiff_t
?
是的,这就是该类型的用途。
3: How do I output variables of type size_t and ptrdiff_t in C and C++?
在 C 中:
printf("%zu %td\n", size, ptrdiff);
在 C++ 中:
std::cout << size << ' ' << ptrdiff << '\n';
4: is
uintptr_t
is just another name forsize_t
OR it should be used as a separate type fromsize_t
?
它应该被视为一个单独的类型。 uintptr_t
是一个整数类型,可以包含任何转换为整数的指针值;它在某些平台上可能不存在。
5: is
ssize_t
andintptr_t
anther name forptrdiff_t
OR it has to be used differently?
ssize_t
就 C 或 C++ 语言而言,它不是标准类型;它被 Posix 定义为一些函数参数和返回值的类型。最好使用ptrdiff_t
除非直接处理 Posix 函数。
intptr_t
用于保存指针的整数表示,而不是指针之间的差异。在某些平台上,这些可能有不同的大小,intptr_t
可能根本没有定义,所以它们不应该互换使用。
I do want to be able to use negative offsets. And any difference in using
uintptr_t
andintptr_t
?
不要使用这两种类型中的任何一种来表示偏移量;使用 ptrdiff_t
.在特殊情况下使用这些类型,当您出于某种原因想要将指针转换为整数表示时。
关于c++ - size_t 和 ptrdiff_t 类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7956763/