Search code examples
catoi

Understanding atoi(var-1) versus atoi(var)-1?


I had an issue where my C program allocated input data correctly only for values less than 5. I found the error in the creation of the int array holding the values: I had used atoi(var-1) instead of atoi(var)-1.

When var='5', atoi(var-1) is 0 when printed out. Why is the number "5" where the erroneous char to int conversion breaks? And why does it become zero at that point?

I'm just curious about what actually happens with this.


Solution

  • Pointer arithmetic. If var is a string (char *), then var + n is the substring starting at offset n.

    const char* s = "12345":
    printf("%d\n", atoi(s + 2));  // prints 345
    

    Subtraction is allowed as well: var - 1 is a pointer to one character before the string. This may be anything, but is probably a non-digit character, so atoi returns 0.