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 typenodeptr
with the size 29989? -
for i = [0, NHASH]
Does this command exist in C? It's just a way
abbreviated to afor(;;)
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
}