ptrdiff_t 的用法

Usage of ptrdiff_t

我正在通过连续的内存块实现迭代器,并遇到了有关其一致性用法的问题。我当前的实现(假设我正在遍历 chars 的数组)。

typedef struct iterator{
    void *next_ptr;
    void *limit; //one past last element pointer
} iterator_t;

void *next(iterator_t *iterator_ptr){
    void *limit = iterator_ptr -> limit;
    void *next_ptr = iterator_ptr -> next_ptr;
    ptrdiff_t diff = limit - next_ptr;
    if(diff <= 0){
        return NULL;
    }
    iterator_ptr -> next_ptr = ((char *) next_ptr) + 1;
    return next_ptr;
}

问题是 6.5.6(p9) 的标准声明:

When two pointers are subtracted, both shall point to elements of the same array object,or one past the last element of the array object

这是真的。我假设我正在迭代的区域是一个数组。

If the result is not representable in an object of that type, the behavior is undefined. In other words, if the expressions point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i−j provided the value fits in an object of type ptrdiff_t.

ptrdiff_t 的限制定义在 7.20.3(p2):

limits of ptrdiff_t

PTRDIFF_MIN −65535

PTRDIFF_MAX +65535

不保证所有用 size_t 表示的值都应该用 ptrdiff_t 表示。

所以我们根据限制判断我们可以符合减去最多只有65535个元素的数组的指针?所以这在我想减去指向未知大小数组元素的两个指针的一般情况下不起作用?

来自规范(第 7.20.3 节)

Its implementation-defined value shall be equal to or greater in magnitude (absolute value) than the corresponding value given below

[强调我的]

所以提到的值只是最小值。实施可能有更大的限制。我希望 ptrdiff_t 是目标平台的字长(即 64 位系统的 64 位类型)。

注意 size_tunsigned 整数类型,而 ptrdiff_tsigned 整数类型.这种暗示并非 size_t 的所有值都可以由 ptrdiff_t.

表示

这似乎是 C 标准本身的问题。

如您所述,6.5.6 Additive operators, paragraph 9 部分指出:

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i-j provided the value fits in an object of type ptrdiff_t. ...

C 标准似乎无法保证您可以在 ptrdiff_t.

中表示两个指针的差异

实际上,这意味着 ptrdiff_t 必须大于 size_tsize_t 只需要覆盖固定位数的大小。 ptrdiff_t 必须涵盖大小和方向。如果 sizeof( size_t ) == sizeof( ptrdiff_t ),则不能保证 6.5.6p9 中的未定义行为不会被调用。