C - htoi function

Solution 1:

You have a missing set of curly braces after your for statement! As it stands, the body of the loop is only the following code:

        if (s[i] >= '0' && s[i] <= '9') {
            hexdigit = s[i] - '0';
            n = 16 * n + hexdigit;
        }

This is because, without a {...} delimited block immediately following the for statement, then only a single statement is used for the loop (and this 'single statement' is the entire first if block). Adding the relevant { on the for line (or on the line after it, if you prefer) and the corresponding } after your third if block fixes the code:

    for (; i < strlen(s); ++i) { // Note the added "{" - which 'starts' the loop's block!
        if (s[i] >= '0' && s[i] <= '9') {
            hexdigit = s[i] - '0';
            n = 16 * n + hexdigit;
        }
        if (s[i] >= 'A' && s[i] <= 'F') {
            hexdigit = s[i] - 'A' + 10;
            n = 16 * n + hexdigit;
        }
        if (s[i] >= 'a' && s[i] <= 'f') {
            hexdigit = s[i] - 'a' + 10;
            n = 16 * n + hexdigit;
        }
    } // And this "}" closes the loop!

In your code, there is no test for the "A..F" and "a..f" characters inside the loop, so any such in the hex number will be ignored (treated as zero). When the two subsequent if tests are executed, s[i] will be pointing to the nul terminator of the string.