0

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;
}
4

1 回答 1

2

直觉上它看起来应该给出一个负索引:

不,因为strchr返回一个指向该字符所在位置的指针。因此,每次strchr返回 non-NULL时,与它开始的指针相比,该指针将位于“更下方”的某个位置。

于 2013-09-02T18:27:57.257 回答