Question

Trying to build a hashtable using linked lists

Asked by: Sandra-24

I'm building a hash table that is actually three hash tables, each one for storage of a specific type, shorts, longs, and c-strings. Such a hash table would make for fats and convenient storage and retrieval of said data types by a string key.  It would also be possible to add a method for saving the data to a file to the hashtables destructor, and a method for reloading this information to the constructor. I plan to do this later, then I would have a very simple method of saving information that would keep it's state between application sessions (usefull in most any app, and won't require any external libraries).

Still with me? I have created the basics of this hash table but I'm obviously misunderstanding some critical C++ concept because it spews compiler errors. I suspect the problem lies with the structs. My code is below:

-----------------------------------------------------------------------------------
DATA.H:

#define NULL 0; //temp null define, should probably add an #ifndef statement or something to it

class data
{
public:
      data(int hashTableLength);
      ~data();
      // Adds a long integer value to the hash table under the 32bit hash key given
      void Add(const long value, const char * key);
      
      // Gets a long integer value from the hash table at the given 32 bit hash key
      long GetLong(const char * key);

private:

      LONG ** longs;
      int hashTableLength;
};

typedef struct {
      long hash = 0;
    LONG * next;
      long data;
} LONG;

-----------------------------------------------------------------------------------
DATA.CPP:

#include "data.h"

data::data(int hashTableLength)
{
      longs = new LONG * [hashTableLength];
      //init all the pointers at NULL (to prevent stray pointer errors)
      for(int i=0; i < hashTableLength; i++)
      {
            longs[i] = NULL;
      }
      //store the length for future usage.
      this->hashTableLength = hashTableLength;
}

data::~data()
{
      //store the data to disk and free all the memory used      

}

// Adds a long integer value to the hash table under the 32bit hash key given
void data::Add(const long value, const char * key)
{
      long hash = strHash(key,strlen(key));
      int index = (int)(hash % hashTableLength); //0-49 for a length of 50

      LONG * entry = longs[index];

      while((entry->next != NULL) && (entry->hash != hash))
      {
            entry = entry->next;
      }

      //so now, this entry->next pointer is either NULL (making it the lest entry)
      //or we've stumbled across an existing entry by this key.
      if(entry->hash == hash)
      {
            entry->data = value;
      }
      //else we need to add a new entry to the end
      else
      {
            entry->next = new LONG; //add a new struct
            entry = entry->next; //set entry to point to the new struct
            entry->next = NULL; //set the next pointer to NULL (we're at the end after all)
            //set the data for this struct
            entry->hash = hash;
            entry->data = value;
      }

}


long data::GetLong(const char * key)
{
      long hash = strHash(key,strlen(key));
      int index = (int)(hash % hashTableLength); //0-49 for a length of 50

      LONG * entry = longs[index];

      while((entry != NULL) && (entry->hash != hash))
      {
            entry = entry->next; //set entry to point to the next LONG struct
      }

      if(entry == NULL)
            return 0; //not found
      else
            return entry->data;
}

-----------------------------------------------------------------------------------
COMPILER ERRORS:

data.h(19): error C2501: 'data::longs' : missing storage-class or type specifiers
data.cpp(33): error C2039: 'next' : is not a member of 'LONG'
data.cpp(6): error C2065: 'longs' : undeclared identifier
data.cpp(12): error C2109: subscript requires array or pointer type
data.cpp(31): error C2109: subscript requires array or pointer type
data.cpp(33): error C2143: syntax error : missing ')' before ';'
data.cpp(33): error C2143: syntax error : missing ')' before ';'
data.h(19): error C2143: syntax error : missing ';' before '*'
data.h(32): error C2143: syntax error : missing ';' before '*'
data.h(32): error C2501: '$UnnamedClass$0x5a7588c4$1$::LONG' : missing storage-class or type specifiers
data.h(32): error C2501: '$UnnamedClass$0x5a7588c4$1$::next' : missing storage-class or type specifiers
data.h(19): error C2501: 'data::LONG' : missing storage-class or type specifiers

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-08-07 at 13:36:18ID20703276
Tags

c2039

,

hashtable

Topics

C++ Programming Language

,

Microsoft Visual C++

Participating Experts
5
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. MSVC++   error C2440: 'type cast' : cannot conv…
    ------------------------------------------ struct testrec { LPTSTR key; LPTSTR data; }; typedef struct testrec rec; int CTestExtension::compare(LPTSTR *str1, LPTSTR *str2) { /* Compare all of both strings: */ return _tcscmp( *str1, *str2 ); } void CTestExtension:...
  2. typedef struct
    Hi, I've written a program that receives some data over a socket connection. I receive the data as a character array.... char *pData=(char*)calloc(1,USSP_RESSIZE); while(nError == WSAEWOULDBLOCK) { nBytes = socket.Receive(pData, USSP_RESSIZE, MSG_PEEK); switch(nB...
  3. HashTable .....
    Hi C++ Experts, I am trying to understand a HashTable class template and its implementation. But there are several places I couldn't figure out why. I would appreciate some helps. Here is the class template of a HashTable : (from Data Structure with C++, Schaum's) ---...
  4. More help with hash function & typedef
    I have decided to work with typedef structs that Kent helped me with earlier. Since I am new with typedefs I am having quite a few warnings. Can anyone look over this code and explain why I am getting mismatch errors? this is what I am trying to do build the hash table ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jkrPosted on 2003-08-07 at 13:42:31ID: 9103193

I'd start by adding

typedef long LONG;

 

by: VEngineerPosted on 2003-08-07 at 13:42:37ID: 9103196

First thing to try is in your header file.. either define your struct before your class, or add a prototype of the struct.  For instance:

// you don't need to redefine NULL

#ifndef DATA_H
#define DATA_H

// forward declaration of type LONG
struct LONG;

class data
{
      public:
            data(int hashTableLength);
            ~data();

            void Add(const long value, const char * key);
            long GetLong(const char * key);

      private:
            LONG ** longs;
            int hashTableLength;
};


// definition of struct LONG

struct LONG {
    long hash = 0;
    LONG * next;
    long data;
};


#endif


That should get a few errors out of the way to start..

 

by: AssafLaviePosted on 2003-08-07 at 13:44:16ID: 9103206


all your errors seem to stem from using 'LONG' instead of 'long'. C++ is case sensitive. if you really want to use LONG instead of long for some reason you'll have to typedef it.
typedef long LONG

 I suggest you just search and replace LONG for long and recompile.

 

by: VEngineerPosted on 2003-08-07 at 13:46:06ID: 9103218

> I'd start by adding
> typedef long LONG;

I think that won't help the case here.  Sandra-24 is trying to define a structure named LONG.
long is already a predefined type in C++ (long integer).

 

by: Sandra-24Posted on 2003-08-07 at 16:35:26ID: 9104283

The solution turned out to be declaring the struct as

typedef struct nodeLong {
      long hash;
        struct nodeLong * next;
      long data;
} nodeLongType;

and replacing all references to LONG with nodeLongType.

in the previous code I was declaring a pointer to LONG in the struct, but of course LONG is only defined as a type after the struct has been defined!

Thanks to all who responded - actually just to VEngineer, who was the only one to read the question carefully enough to spot that LONG was a struct, not a long integer.

 

by: shajithchandranPosted on 2003-08-07 at 21:48:04ID: 9105675

hi,

At last i got the problem.
The problem is with
#define NULL 0;
That ; after the 0 is the source of all the error.

Remove that ";" and it will compile properly.
Any way there is no need to define NULL again as it is define already.

Shaj.

 

by: Sandra-24Posted on 2003-08-07 at 23:25:37ID: 9106036

Yes shaj, I forgot to mention I also had to ditch the define NULL. Sorry you didn't see my post above, you went to all that work for nothing! Well almost nothing, I'll hand out points for this anyway.

 

by: dennis_georgePosted on 2003-08-07 at 23:42:14ID: 9106109

Hi,

*I assume that you are using turbo C for compiling your program because LONG is already typecast as long in VC++ environment
typedef LONG long...
So it is wrong to use LONG -> already defined........
So first thing change LONG to some other name like _LONG

* Second the member variable "data" of   LONG is same as the class name "data" so change their name...
  like

typedef struct {
    long hash;
   _LONG *next;
    long ldata;  // change the name
}_LONG;          

since class data is using _LONG take the structure above class data or forward declare _LONG.

* strHash was not define...... So define it somewhere.... as a function or #define.... like

 #define strHash(str, key) key/2

I just modified your program a little bit......

check it out

//**************************************************************
#include <iostream.h>
#include <string.h>

typedef struct {            // The definition of _LONG is moved up
    long hash;
   _LONG *next;
    long ldata;
}_LONG;     // name modified

#define strHash(str, key) key/2     // strHash defined

class data
{
public:
    data(int hashTableLength);
    ~data();
    // Adds a long integer value to the hash table under the 32bit hash key given
    void Add(const long value, const char * key);

     // Gets a long integer value from the hash table at the given 32 bit hash key
    long GetLong(const char * key);

private:

    _LONG **longs;
    int hashTableLength;
};


//-----------------------------------------------------------------------------------
//DATA.CPP:

#include "data.h"

data::data(int hashTableLength)
{
    longs = new _LONG * [hashTableLength];
    //init all the pointers at NULL (to prevent stray pointer errors)
    for(int i=0; i < hashTableLength; i++)
    {
         longs[i] = NULL;
    }
    //store the length for future usage.
    this->hashTableLength = hashTableLength;
}

data::~data()
{
    //store the data to disk and free all the memory used

}

// Adds a long integer value to the hash table under the 32bit hash key given
void data::Add(const long value, const char * key)
{
    long hash = strHash(key,strlen(key));
    int index = (int)(hash % hashTableLength); //0-49 for a length of 50

    _LONG * entry = longs[index];

    while((entry->next != NULL) && (entry->hash != hash))
    {
         entry = entry->next;
    }

    //so now, this entry->next pointer is either NULL (making it the lest entry)
    //or we've stumbled across an existing entry by this key.
    if(entry->hash == hash)
    {
         entry->ldata = value;
    }
    //else we need to add a new entry to the end
    else
    {
         entry->next = new _LONG; //add a new struct
         entry = entry->next; //set entry to point to the new struct
         entry->next = NULL; //set the next pointer to NULL (we're at the end after all)
         //set the data for this struct
         entry->hash = hash;
         entry->ldata = value;
    }

}


long data::GetLong(const char * key)
{
    long hash = strHash(key,strlen(key));
    int index = (int)(hash % hashTableLength); //0-49 for a length of 50

    _LONG * entry = longs[index];

    while((entry != NULL) && (entry->hash != hash))
    {
         entry = entry->next; //set entry to point to the next _LONG struct
    }

    if(entry == NULL)
         return 0; //not found
    else
         return entry->ldata;
}




Hope this will work.....
Dennis

 

by: VEngineerPosted on 2003-08-08 at 11:55:13ID: 9110377

Good to hear you found a solution.

From what I understand in C++, what you have:

// the classic way you define structs in C

typedef struct nodeLong {
    long hash;
       struct nodeLong * next;
    long data;
} nodeLongType;


should be completely equivalent to:

// the way I've always defined structs in C++

struct nodeLongType {
    long hash;
    nodeLongType * next;
    long data;
};


This being said, classes and structs are the same in C++, except members of a class are private by default and members of a struct are public by default.  Yep, a struct in C++ can have member functions as well as data members.  So defining them is the same and we don't need to fuss with typedefs and using the struct keyword for recursive types like the node you have here :)  Just something to think about.

 

by: Sandra-24Posted on 2003-08-09 at 01:09:33ID: 9113136

I never realized that, I'll keep that in mind in future.

A struct with member functions - what next?

lol.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...