Understanding an atoi() function

Craig picture Craig · Oct 31, 2011 · Viewed 17.1k times · Source

I'm a python programmer getting to learn C from the K&R book. This will seem like an awfully trivial question, but I'm stumped nonetheless. Attached below is a snippet of code from the K&R (RIP Ritchie!) book which implements the atoi() function.

atoi(s) /*convert s to integer */
char s[];
{
    int i, n, sign;
    for (i=0; s[i]==' '||s[i] == '\n' || s[i] == '\t'; i++)
    ;   /* skip whitespace */
    sign = 1;
    if (s[i] == '+' || s[i] = '-')  /* sign */
        sign = (s[i++] == '+') ? 1 : -1;
    for (n=0; s[i] >= '0' && s[i] <= '9'; i++)
        n = 10 * n + s[i] - '0';
    return (sign * n);
}

My questions:

1) Does the first 'for' loop serve any purpose besides counting the number of valid characaters?
2) If (1) is true, the first loop sets the value of 'i' to the number of valid characters - how does the second for loop work without reseting i to 0?

Say for example I enter '2992' as an input to the function. The first for loop sets i to 3, so how does the rest of the function work? I may have my basics all messed up but any help would be really appreciated. Thanks, -Craig

Answer

alice7 picture alice7 · Oct 31, 2011
int atoi(char* str)
{
    if(!str)
        printf("Enter valid string");

    int number = 0;
    char* p = str;

    while((*p >= '0') && (*p <= '9'))
    {
        number = number * 10 + (*p - '0');
        p++;
    } 
    return number;
}

Here is the whole idea behind ATOI.

1) You set the pointer at the start of the char array

2) And then inside while loop you go over each character and multiply by 10 and add the character by subtracting by 0.

And if you will try with 2992. the number would be 2992 as well.