gpt4 book ai didi

c - 如何计算两个地址之间的距离?

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:08 25 4
gpt4 key购买 nike

我想计算两个地址之间的字节数。

uint32_t length = &b - &a;

enter image description here

当a和b为uint32_t时,length为1。

uint32_t a, b;
uint32_t length = &b - &a; // length is one

当a和b为uint8_t时,长度为4。

uint8_t a, b;
uint32_t length = &b - &a; // length is four

因此,计算是 a 和 b 之间的 uint32_t 或 uint8_t 的数量,而不是我错误预期的地址之间的数学差异。

我的问题:C 语言的哪一部分涉及地址计算?有人可以引用规范中讨论该主题的位置吗?

最佳答案

指针减法在 C standard 的第 6.5.6 节中介绍。 :

3 For subtraction, one of the following shall hold:

  • both operands have arithmetic type;
  • both operands are pointers to qualified or unqualified versions of compatible complete object types; or
  • the left operand is a pointer to a complete object type and the right operand has integer type.

...

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 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. Moreover, if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)-(P) has the same value as ((Q)-(P))+1 and as -((P)-((Q)+1)), and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object.

所以区别在于两者之间的元素个数,而不是字节数。

请注意,这只允许在同一数组的两个元素之间减去指针。所以这是合法的:

uint32_t a[5];
uint32_t len = &a[1] - &a[0];

但这不是:

uint32_t a, b
uint32_t len = &b - &a;

关于c - 如何计算两个地址之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740250/

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