看不懂strchr在C中获取字符串中某个字符位置的用法

Can't understand the usage of strchr to get the position of a charcter in a string in C

此代码将输出字符串中字符的索引:

#include <stdio.h>
#include <string.h>

int main(void){

   char str[100]="birds are dying";
   char *p;

   p = strchr(str,'e'); 
   int i=p-str;

   printf("%d" , i);

   return 0;
}

我唯一无法理解的代码行是:

int i=p-str;
  1. str 是字符串,p 也是,我搜索了将字符串打印为整数的结果,发现它是未定义的行为,那么它实际上是什么 return?

  2. p - str 是:e dying - birds are dying,当我们以某种方式将其更改为整数时,为什么它 return 是正值

谢谢

它不是一个字符串 - 它是一个指针。这是合法的指针运算。它以指针为单位工作。假设你有

double x[10], *start, *end;
integer exclusive;

start = &x[2];
end = &x[4];
exclusive = end - start;
printf("%d\n", exclusive);

你认为会打印什么?你会得到 2: not 2 * sizeof(double).

来自 C 标准(6.3.2.1 左值、数组和函数指示符)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined

在本次通话中

p = strchr(str,'e');

函数strchrreturns指向符号'e'.

的指针

在表达式中

p-str

具有数组类型 char[100] 的对象 str 被隐式​​转换为指向其第一个元素的指针。所以表达式表示两个指针的不同。

并且根据 C 标准(6.5.6 加法运算符)

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....

因此,差值是两个指针之间元素的数量,这两个指针产生找到的符号的索引,因为表达式 str(在数组 str 隐式转换为指针之后)指向数组的第一个元素。