开发者

What is the point of subtracting in this index of an array?

main()
{
    int c, i, n开发者_StackOverflow中文版white, nother;
    int ndigit[10];

    nwhite = nother = 0;
    for (i=0; i<10; i++)
        ndigit[i]=0;

    while((c=getchar()) != EOF)
        if(c>='0' && c<='9')
            ++ndigit[c-'0'];
        else if(c==' ' || c=='\n' || c == '\t')
            ++nwhite;
        else
            ++nother;

    printf("digits =");
    for(i=0; i<10; ++i)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %d\n", nwhite, nother);


}

What is the point of having the index like this? ++ndigit[c-'0']; As opposed to this: ++ndigit[c]; or am I totally looking at this the wrong way?


The ASCII character for 0 is not the actual zero byte \0. Thus, if you did a['0'], you would actually be doing a[48] (on an ASCII system), and so subtracting '0' converts the digit to an integer value.


In this case, when you use getchar(), it returns an int but with the values of a char. In chars the numbers '0' to '9' aren't actually stored numerically as 0 to 9 but as 48 to 57. That is to say '0' is not the same as 0 but actually the same as 48. Therefore, in this case, let's say c is '0'. If you just did nDigits[c] it would be the same as nDigits[48] when what you want is nDigits[0] so you need to do nDigits[c - '0'] which translates to nDigits[48 - 48] which is nDigits[0]... which is what you want!


getChar() is returning a character. So c-'0', if c == '0'. results in the integer 0.


ndigit[c] will get you an array index somewhere around the ascii value of '0'->'9', or 48-57. By subtracting '0', you bring it down to the 0 to 9 range.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜