Search code examples
cpointer-arithmetic

Problem with strchr


I can't get why the following bit of C code doesn't work:

int obtainStringLength(char* str, char c1, char c2) {
    char* firstOcurrence = strchr(str, c1);
    char* endOcurrence = strchr(str, c2);
    return 2+(endOcurrence - firstOcurrence) / sizeof(char*);
}

The idea is to find how many characters are between c1 and c2:

printf("%d\n", obtainStringLength("abc def ghi", 'a', 'i')); //should yield 11

Unfortunately, this is always printing 1. What is the problem? Shouldn't strchr work like C#'s string.IndexOf()?


Solution

  • Division by sizeof(char*)? That's incorrect - the result of subtracting two pointers is a numerical value (ptrdiff_t) corresponding to the number of values, not a pointer or difference of addresses.

    There's also the off-by-one error in calculating the length. So that last line should look like:

    return 1 + (endOcurrence - firstOcurrence);