[英]What is the role of -s in this code, where s is a char pointer?
In this code在这段代码中
strcpy(s, "bacalaureat");
i = strchr(s, 'a') - s; // i = 1
The value of i
is 1. Why is that, and what's the role of the -s
above? i
的值是1。为什么会这样,上面的-s
的作用是什么?
char *strchr( const char *str, int ch );
Finds the first occurrence of
ch
... in the null-terminated byte string pointed to bystr
在
str
指向的以空字符结尾的字节字符串中查找第一次出现的ch
...
So strchr(s, 'a')
will return a pointer to the first occurrence of the character a
, which is the second character in s
.所以
strchr(s, 'a')
将返回一个指针,指向第一次出现的字符a
,这是s
中的第二个字符。
Subtracting s
from this result is just pointer arithmetic which gives you the index of the character a
in s
, which is 1.从此结果中减去
s
只是指针运算,它为您提供s
中字符a
的索引,即 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.