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

标签 c pointers memory byte sizeof

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

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/

相关文章:

c - C中十六进制字符串到字节数组

c - C语言中如何通过指针访问矩阵数组的元素?

c - 使用条件运算符时变量值如何变化?

c++ - boost 的托管内存中的内存对齐约束

android - Android 上的 UI 元素之间是否共享图像资源?

c - 递归选择排序在 C 中输出不正确的值

c - 如何将这些数字存储在 C 中?

c - 在这些条件下设置变量原子

c - 设置所需内存地址错误

memory - I/O映射的I/O-端口地址是RAM的一部分