Optimized word counter in C

Asked

Viewed 405 times

2

I’m trying to understand an example of code in C to count words (from the book Programming Pearls). But I’m having doubts in some parts of the code (maybe I didn’t type correctly):

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

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

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 
}
  • I’m much more interested in data structure now, and I haven’t taken a lot of classes in college.

1 answer

3


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

Correct.

for i = [0, NHASH] Does this command exist in C? It is just a form abbreviated from a for loop(;;)?

It really doesn’t make any sense in C and I believe in any language, at least none that I know of.

for(;;) is a loop infinite.

Actually 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))

I put in the Github for future reference.

Missing endpoint and comma on virtually all lines.

  • Instead of typing, I picked up looked at the source: int main()&#xA;{ int i;&#xA; nodeptr p;&#xA; char buf[100];&#xA; for (i = 0; i < NHASH; i++)&#xA; bin[i] = NULL;&#xA; while (scanf("%s", buf) != EOF)&#xA; incword(buf);&#xA; for (i = 0; i < NHASH; i++)&#xA; for (p = bin[i]; p != NULL; p = p->next)&#xA; printf("%s %d\n", p->word, p->count);&#xA; return 0;&#xA;}

  • I will redo this function in JS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.