简体   繁体   中英

strchr(), How does this correctly find the index of a char

I'm looking at the example for strchr() on: http://www.cplusplus.com/reference/cstring/strchr/

Why does this correctly find the index? Intuitively it looks like it should be giving a negative index:

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

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}

Intuitively it looks like it should be giving a negative index:

No, because strchr returns a pointer to the place where that character is found. So every time strchr returns non- NULL , that pointer it will be somewhere "further down" compared to the pointer where it started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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