did not understand a point of following the program

Hi,
did not understand a point of following the program

pch-str + 1

exactly what`s going on here?

1
2
3
4
5
6
7
8
9
int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  pch=strrchr(str,'s');
  printf ("Last occurence of 's' found at %d \n",pch-str + 1);
  return 0;
}



Last occurence of 's' found at 18



thank in advances.

lets say the string starts at address 1002.
and s is found at address 1019.

so 1019 - 1002 + 1 = 18

the string is zero based so adding 1 will give a human readable count.
Last edited on
Is there another way to do this ?
You can simply modify this example:
1
2
3
4
5
6
7
8
9
10
11
12

int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  pch=strrchr(str,'s'); 
  printf ("Begining of the str: %p \n",str);
  printf ("Last occurence of 's' found at address: %p \n", pch);

  printf ("Last occurence of 's' found at %d \n",pch-str + 1);
  return 0;
}


My result of this program is:

1
2
3
  Begining of the str:  0xbfc57824
  Last occurence of 's' found at address: 0xbfc57835
  Last occurence of 's' found at 18


subtract 35 and 24 (in HEX) and get 17 (in dec)
17 + 1 = 18

yes there is another way:

int string_length = calculate_string_length(str);

loop(string_length to zero)
as soon you find the character you are looking for, break the loop

print the value of string_length.
thank everyone you for your responses.
Topic archived. No new replies allowed.