【发布时间】:2013-07-22 08:50:45
【问题描述】:
我目前正在阅读 Kernighan & Richie 的“The C Programming Language”,我正在努力弄清楚一行的作用。我想我只是有点愚蠢,并不太理解他们的解释。
++ndigit[c-'0'];
我不得不稍微改变程序,因为ndigit 之前给了我垃圾值,所以我只是将数组实例化为 0,而不是使用 for 循环遍历它,并以这种方式更改值。
#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);
}
使用程序作为输入,我们将其打印到控制台 -
digits = 7 2 0 0 0 0 0 0 0 1, white space = 104, other = 291
我知道7 2 0 0 0 0 0 0 0 1 是单个数字在输入中出现的次数的计数 0 出现 7 次,1 出现两次等)
但是,...[c-'0'];“工作”是如何工作的?
【问题讨论】:
标签: c arrays kernighan-and-ritchie