M
mdh
Hi all,
I have a question about an aspect of the hash table implementation
from p 145.
The code, stripped as far as possble, is as follows.
/*******/
#define HASHSIZE 101
struct nlist{
struct nlist *next;
char *defn;
char *name;
};
struct nlist *hashtable[HASHSIZE];
struct nlist *install( char *name, char *defn);
int main (int argc, const char * argv[]) {
struct nlist *np;
np = install("test", "12");
}
struct nlist *install( char *name, char *defn){
struct nlist *np;
unsigned hashval;
if ( (np=lookup(name) )== NULL) {
np= malloc(sizeof(*np));
if ( np == NULL || (np->name = str_dup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtable[hashval]; /******** Question 1*******/
hashtable[hashval]=np;
}
else
free((void *) np->defn); /********* Question 2 **********/
if ( ( np->defn = str_dup(defn)) == NULL)
return NULL;
return np;
}
Question 1;
What exactly does this line do? It seems to be assigning a pointer at
element "hasval" to the member nlist.next, but my question is
why? I assume to create the linked list...but the logic escapes
me.
Question 2:
free casts np-> defn to a void pointer. K&R do not go into great
detail about free here, but seeing that free and malloc seem tied
close together, does the admonition of not using a cast in malloc
apply to free to. Of note, the errata pages do not make mention of
this.
Thanks as always.
I have a question about an aspect of the hash table implementation
from p 145.
The code, stripped as far as possble, is as follows.
/*******/
#define HASHSIZE 101
struct nlist{
struct nlist *next;
char *defn;
char *name;
};
struct nlist *hashtable[HASHSIZE];
struct nlist *install( char *name, char *defn);
int main (int argc, const char * argv[]) {
struct nlist *np;
np = install("test", "12");
}
struct nlist *install( char *name, char *defn){
struct nlist *np;
unsigned hashval;
if ( (np=lookup(name) )== NULL) {
np= malloc(sizeof(*np));
if ( np == NULL || (np->name = str_dup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtable[hashval]; /******** Question 1*******/
hashtable[hashval]=np;
}
else
free((void *) np->defn); /********* Question 2 **********/
if ( ( np->defn = str_dup(defn)) == NULL)
return NULL;
return np;
}
Question 1;
What exactly does this line do? It seems to be assigning a pointer at
element "hasval" to the member nlist.next, but my question is
why? I assume to create the linked list...but the logic escapes
me.
Question 2:
free casts np-> defn to a void pointer. K&R do not go into great
detail about free here, but seeing that free and malloc seem tied
close together, does the admonition of not using a cast in malloc
apply to free to. Of note, the errata pages do not make mention of
this.
Thanks as always.