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 typenodeptr
with the size of 29989?for i = [0, NHASH]
Does this command exist in C? It’s just a form
abbreviated from a loopfor(;;)
?
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.
– Marcus Becker