C Array Count (Beginner) [duplicate]

2020-03-07 07:53发布

I'm currently reading 'The C Programming Language' by Kernighan & Richie and I'm struggling to work out what a line does. I think I'm just being a little stupid, and not quite understanding their explanation.

++ndigit[c-'0'];

I've had to change the program ever so slightly as ndigit was previously giving me garbage values, so I just instantiate the array to 0, instead of traversing it with a for loop, and changing the values that way.

#include <stdio.h>

main()
{
    int c, i, nwhite, nother;
    int ndigit[10]= {0};

    nwhite = nother = 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);
}  

Using the program as its input, we get this printed to the console -

digits = 7 2 0 0 0 0 0 0 0 1, white space = 104, other = 291

I understand that 7 2 0 0 0 0 0 0 0 1 is a count of how many times the single numbers appear in the input 0 appears 7 times, 1 appears twice etc.)

But, how does the ...[c-'0']; 'work'?

8条回答
Emotional °昔
2楼-- · 2020-03-07 08:51

You asked how the below expression works

 c-'0'

The ASCII code of the entered charecter is subtracted from the ASCII code of 0 and it defines the position in the array where the count has to be stored .

Suppose you enter 1 from the keyboard ASCII code for 1 is 49 and ASCII code for 0 is 48. hence

   49-48 =1 

and the count will be stored in the array index location 1 .

查看更多
唯我独甜
3楼-- · 2020-03-07 08:52

c-'0' is technique to give int value == to char number e.g. 1 for '1' , 5 for '5'.

char symbols '0', '1', '2' ..... '9' are assigned continue encoding values so difference of a numeric char constant with '0' gives decimal number. (in your compiler for example in ASCII char they are assigned continues acsii values).

So for example in variable c is '7', then c - '0' == 7;

In your code array declared as:

int ndigit[10]= {0};   
                // default initialized with `0`

So index can be from 0 to 9. So in you code:

++ndigit[c-'0'];  // ndigit[c-'0'] = ndigit[c-'0'] + 1;

increments frequency of a number by 1 when at corresponding digit of a number char.

查看更多
登录 后发表回答