"The C Programming Language", 2nd edition, Kernighan and Ritchie

Answer to Exercise 6-5, page 145

Solutions by Paul Griffiths and Gregory Pietsch

Write a function undef that will remove a name and definition from the table maintained by lookup and install .



int undef(char * name) {
    struct nlist * np1, * np2;

    if ((np1 = lookup(name)) == NULL)  /*  name not found  */
        return 1;

    for ( np1 = np2 = hashtab[hash(name)]; np1 != NULL;
          np2 = np1, np1 = np1->next ) {
        if ( strcmp(name, np1->name) == 0 ) {  /*  name found  */

            /*  Remove node from list  */

            if ( np1 == np2 )
                hashtab[hash(name)] = np1->next;
            else
                np2->next = np1->next;

            /*  Free memory  */

            free(np1->name);
            free(np1->defn);
            free(np1);

            return 0;
        }
    }

    return 1;  /*  name not found  */
}




Gregory Pietsch's solution

void undef(char *s)
{
    struct nlist *np1, *np2;
    unsigned hashval = hash(s);

    for (np1 = hashtab[hashval], np2 = NULL; 
         np1 != NULL;
         np2 = np1, np1 = np1->next) 
        if (strcmp(s, np1->name) == 0) {
            /* found a match */
            free(np1->name);
            free(np1->defn);
            if (np2 == NULL) 
                /* at the beginning? */
                hashtab[hashval] = np1->next;
            else 
                /* in the middle or at the end? */
                np2->next = np1->next;
            free(np1);
            return;
        }
}




Back to index





You are visitor number - call again soon!