tags:

views:

107

answers:

2

Hi so I have the following code and I want to be able to insert words into it and be able to see the stuff I put into the hash by printing it out. Here's what I have:

#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <set>
#include <windows.h>

using namespace std;

struct nlist{
    struct nlist *next;
    char *name;
    char *defn;
};

#define HASHSIZE 101

static struct nlist *hashtab[HASHSIZE];

unsigned hash(const char *s)
{
    unsigned hashval;

    for (hashval = 0; *s != '\0'; s++)
     hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

struct nlist *lookup(const char *s)
{
    struct nlist *np;

    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
     if (strcmp(s,np -> name) == 0)
      return np;
    return NULL;
}

struct nlist *install(const char *name, const char *defn)
{
    struct nlist *np;
    unsigned hashval;

    if ((np = lookup(name)) == NULL){
     np = (struct nlist *) malloc (sizeof(*np));
     if (np == NULL || (np -> name = strdup(name)) == NULL)
      return NULL;
     hashval = hash(name);
     np->next = hashtab[hashval];
     hashtab[hashval] = np;
    }
    else{
     free((void *) np->defn);

    }
    if ((np -> defn = strdup(defn)) == NULL)
     return NULL;
    return np;
}

int main(){

    cout << "yo";
    string inline1;
    while (1){
     getline(cin, inline1);
     if (inline1 == "hash"){
      getline(cin, inline1);
      cout << hash(inline1.c_str()) << '\n';
     }
     else if (inline1 == "lookup"){
      getline(cin, inline1);
      cout << lookup(inline1.c_str()) << '\n';
     }
     else if (inline1 == "install"){
      getline(cin, inline1);
      string inline2;
      getline(cin, inline2);
      cout << install(inline1.c_str(), inline2.c_str()) << '\n';
     }
    }
}
A: 

I recommend reading, or even using, the TR1 unordered_map or the GCC hash_map instead of building from scratch. Or get a copy of Knuth. Debugging this much of a hash table is more work than anyone here is likely to do.

You don't mention a platform, but if it is Windows they also have, depending on which version of visual studio, an STL-ish hash table for your to read and/or use.

bmargulies
+1  A: 

The problem you are having here is that you are printing out the pointer to the nlist item that you have looked up, rather than the value of the defn string within that item.

In your main loop, you have the following code:

else if (inline1 == "lookup"){
        getline(cin, inline1);
        cout << lookup(inline1.c_str()) << '\n';
}

What you probably want instead is:

else if (inline1 == "lookup"){
        getline(cin, inline1);
        cout << lookup(inline1.c_str())->defn << '\n';
}
Brian Campbell