字符指针运算 C

Char pointer arithmetic C

我正在学习指针运算,遇到这样的事情:

char *str1, *str2;

/* stuff in between */

int f = str2 - str1;

str2 - str1 返回了什么?假设 str1 = "foo"str2 = "foobar".

f = str2 中的内存地址 - str1 中的内存地址。 "foo""foobar" 是这些指针指向的这些内存位置的值。

示例:

如果str2 = 0x8000000a

str1 = 0x80000000

str2 - str1 = 0x8000000a - 0x80000000 
str2 - str1 = 0x0a 

已编辑

这个问题的答案要看情况。

1) 在你的情况下,由于指针没有指向任何东西,结果将是垃圾

2) 如果两个指针指向程序中的两个有效内存位置space,那么结果将是这两个位置之间的内存字节数。尽管这没有任何意义,并且根据 C 规范它是 UB,如果两个指针不指向同一个数组或字符串。如果两个指针指向同一个数组或字符串,那么结果将是同一数组中两个元素之间的元素数(当指针指向该数组内的这两个元素时)。检查 this SO 问题以获取示例和更多解释。

您提出问题的结果未定义。为了使指针差分正常工作,它们必须来自相同的数组序列(动态、自动,甚至自动 VLA 都没有区别)。或最后一个元素之后的过去地址:

§6.5.6 Additive Operators (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; 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. 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.106

就是说,如果您改写以符合上述规则,例如:

#include <stdio.h>
int main()
{
    const char *p = "Hello World";
    const char *q = p+7;
    printf("%td\n", q-p);
    return 0;
}

输出

7

并从标准的引用部分解释了原因。