C word counter optimized

2

I'm trying to understand an example of C code to count words (from Programming Pearls). But I am in doubt in some snippets of the code (maybe I have not typed correctly):

  • nodeptr bin[NHASH]; This declares an array of type nodeptr with the size 29989?

  • for i = [0, NHASH] Does this command exist in C? It's just a way
    abbreviated to a for(;;) loop?

Complete code:

typedef struct node *nodeptr;
typedef struct node {
   char *word;
   int count;
   nodeptr next;
} node;

#define NHASH 29989
#define MULT 31
nodeptr bin[NHASH];

unsigned int hash(char *p){
   unsigned int h = 0
   for ( ; *p; p++)
      h = MULT * h + *p

   return h % NHASH
}

int main(void){
   for i = [0, NHASH]
      bin[i] = NULL

   while scanf("%s", buf) != EOF
      incword(buf)

      for i = [0, NHASH]
         for (p = bin[i]; p != NULL; p = p->next)
            print p->word, p->count

   return 0
}

void incword(char *s){
   h = hash(s)

   for (p = bin[h]; p != NULL; p = p->next)
      if strcmp(s, p->word) == 0
         (p->count)++

   return

   p = malloc(sizeof(hashnode))
   p->count = 1
   p->word = malloc(strlen(s)+1)
   strcpy(p->word, s)
   p->next = bin[h]
   bin[h] = p 
}
    
asked by anonymous 18.01.2017 / 20:23

1 answer

3
  

nodeptr bin [NHASH]; This declares an array of type nodeptr with the size of 29989?

Correct.

  

for i = [0, NHASH] Does this command exist in C? It's just a way   abbreviated for a for loop (;;)?

It really does not make sense in C and I believe in any language, at least none that I know of.

for(;;) is an loop infinite.

In fact the whole code seems to have basic syntax problems. Just a few examples:

while scanf("%s", buf) != EOF // Falta parênteses aqui.

for (p = bin[h]; p != NULL; p = p->next) //p não está declarado em lugar algum.

return // Daqui pra frente nada será executado.

p = malloc(sizeof(hashnode))

Final semicolon is missing on virtually every line.

    
18.01.2017 / 20:31