gpt4 book ai didi

c - ptrdiff_t 的使用

转载 作者:太空狗 更新时间:2023-10-29 15:23:09 31 4
gpt4 key购买 nike

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

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_t 是一个无符号 整数类型,而ptrdiff_t 是一个有符号 整数类型。这意味着并非 size_t 的所有值都可以用 ptrdiff_t 表示。

关于c - ptrdiff_t 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361344/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com