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/