strchr() question

I saw some pretty bizzare use of strchr() in a 2009 exam subject..

1
2
3
4
5
  char* s;
  strcpy(s, "info");
  int i = strchr(s, 'i') + s;
  //What does the +s do?
  //Can you even add a char* to a number, or is it a typo? 
That code contains several errors.
s is an uninitialised pointer, so the strcpy() will give rise to undefined behaviour.

The return value of strchr() is a pointer, char *.
Line 3 doesn't compile, it gives an error:
[Error] invalid operands of types 'char*' and 'char*' to binary 'operator+'


An example of valid code based on that fragment could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstring>
#include <iostream>

int main ()
{
    
    char* s = new char[20];
    strcpy(s, "info");
    int i = strchr(s, 'f') - s;
    
    std::cout << "i = " << i << '\n';
   
    delete [] s;
}
i = 2


Note, I used subtraction, not addition. Two pointers of the same type may be subtracted, the result is the offset from the first value to the second, in this case the position within the string s of the character 'f'.

I used 'f' rather than 'i' in this example for two reasons. One, character 'i' is at position 0, a non-zero result is more interesting in understanding what happens. (also, to avoid confusion with the variable i).


http://www.cplusplus.com/reference/cstring/strchr/
Can you even add a char* to a number

Sure.

1
2
3
4
5
6
7
8
9
#include <iostream>

int main ()
{
    const char* s = "abcdef";
    
    std::cout << "*(s + 3) = " << *(s + 3) << '\n';
    std::cout << "s[3]     = " << s[3]     << '\n';    
}
*(s + 3) = d
s[3]     = d


Or perhaps:
1
2
3
    const char* t = "blue moon";
    
    std::cout << t + 5 << '\n';
moon

Last edited on
Thanks! It was substraction after all.
It just seemed very.. bizzare. I'll look more into operations with pointers.
Topic archived. No new replies allowed.