Question

I recently picked up The C Programming Language (2nd ed) and have been working my way through the examples in the book. Arrays are giving me problems. Specifically, it seems to have to do with type-casting. The section 1.6 example reads input and then counts how many characters fall into certain categories. This segment of code seems to be creating a segfault when I pipe the source code through the executable, in addition to not properly catching any numeric characters. If I use standard input and ^D to EOF, then it doesn't catch the numbers at all and instead counts them as other characters (although without segfault).

while ((c=getchar())!=EOF)
  if(c>='0'&&c>='9')
    ++ndigit[c-'0'];

I've eliminated the possibility that it's a different part of the program causing the fault by swapping out other sections, but i could post the rest anyway if it helps. To my understanding, this loop should make its way through individual characters in the input. If they have value between 0 and 9, it converts the character to a number (corresponding to ndigit array position 0-9) and increases that array position by 1.

Is the K&R 2e sorely outdated? Is character encoding (ASCII vs Unicode) an issue in converting the character number to integer number? Any advice would be appreciated.

I'm not sure how to check my encoding (if it even matters) but my compiler is gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

Was it helpful?

Solution

if(c>='0'&&c>='9')

Well you meant:

if(c>='0'&&c<='9')

Also please check that c is correctly declared with type int and not char.

OTHER TIPS

I got stuck on this exercise because of a typo in my array loop.

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

It should have been..

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

note the i and 1 are transposed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top