c++ - size_t 和 ptrdiff_t 类型的变量

标签 c++ c size-t

通过阅读与 size_tptrdiff_t 相关的在线帖子,我想确认以下几点:

  1. 如果数组的最大大小小于 1/2*(max number represent-able by size_t),我可以安全地使用 ptrdiff_t 并且检查指向同一个对象的两个指针之间的相对距离?(因为我说的是数组,所以“指向同一个对象的指针”是指“指向同一个数组的指针”)。

  2. 如果我想声明一个可以表示与另一个指针的偏移量的变量,我最好将其声明为类型 ptrdiff_t ?

  3. 如何在 C 和 C++ 中输出 size_tptrdiff_t 类型的变量?以下是否正确:Cross platform format string for variables of type size_t?

  4. is uintptr_t 只是 size_t 的另一个名称,或者它应该用作 size_t 的单独类型?

  5. ssize_tintptr_t 的另一个名称 ptrdiff_t 还是必须以不同的方式使用?

我开始在 Ubuntu 上使用 gcc。我刚刚在使用某人时发现了这些类型 else 的代码。

添加:我确实希望能够使用 negative 偏移量。以及使用 uintptr_tintptr_t 有什么区别?

最佳答案

1: if the max size of an array is less than 1/2*(max number represent-able by size_t), I can safely use ptrdiff_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 for size_t OR it should be used as a separate type from size_t?

它应该被视为一个单独的类型。 uintptr_t是一个整数类型,可以包含任何转换为​​整数的指针值;它在某些平台上可能不存在。

5: is ssize_t and intptr_t anther name for ptrdiff_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 and intptr_t?

不要使用这两种类型中的任何一种来表示偏移量;使用 ptrdiff_t .在特殊情况下使用这些类型,当您出于某种原因想要将指针转换为整数表示时。

关于c++ - size_t 和 ptrdiff_t 类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7956763/

相关文章:

c - 在 Mandelbrot 集中用鼠标平滑缩放 (C)

c++ - size_t 的大小是否始终等于 void * 的大小

c++ - unsigned int 与 size_t

c++ - 如何强制类的实例只分配在栈上,而不分配在堆上

c - 如何设置void **的值

c - 从 WCHAR 转换为 char 时,为什么会出现额外的空终止字符?

c - 代码说明

c++ - Visual Studio 代码调试 : source and then launch on same shell

c++ - 为什么我的凸包周长计算不起作用?

c++ - 指针 vector 。如何使用?