简体   繁体   English

-s 在这段代码中的作用是什么,其中 s 是一个 char 指针?

[英]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的作用是什么?

From the reference :参考

char *strchr( const char *str, int ch );

Finds the first occurrence of ch ... in the null-terminated byte string pointed to by strstr指向的以空字符结尾的字节字符串中查找第一次出现的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM