Confused about this pointer arithmatic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* strchr example */
#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);///what is this pch-str+1 doing?
    pch=strchr(pch+1,'s');
  }
  return 0;
}
///what is this pch-str+1 doing?

It is subtracting the address of str from pch then adding 1 to that result. Remember pch is a pointer to somewhere in the string whose starting address is str, this number should be the "index" value of the array.

thanks so he should use str type int, not string...
Topic archived. No new replies allowed.