473,763 Members | 7,622 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting a hash table

I have a hash table with seperate chaining with a bunch of words in it.
Here is my declaration:

typedef struct word *word;
struct word
{
int count;
char *s;
word next;
};

typedef struct table *table;
struct table
{
int size;
word *table;
};
After I fill the table(t) with words, I want to sort it with qsort().
However, I know my declaration here is wrong somehow:

total(t) gets the total number of words in the table.
here is my call to qsort():

qsort( t->table, total(t), sizeof(word), compare );
here is my compare() function:

int compare(const void *a, const void *b)
{
word wa = malloc(sizeof(w a));
word wb = malloc(sizeof(w b));

wa = *(const word const *) a;
wb = *(const word const *) b;

if( (wb->count) - (wa->count) == 0 )
{
return( strcmp(wb->s, wa->s) );
}

return ( (wb->count) - (wa->count) );
}

Somehow, wb and wa are not getting the right values. wa seems to get an
actual word but wb is left NULL and i end up with a bus error. Any
advice on this matter would be much appreciated.

Nov 15 '05 #1
4 5857
On 2 Oct 2005 21:10:21 -0700, "dough" <vi****@gmail.c om> wrote in
comp.lang.c:
I have a hash table with seperate chaining with a bunch of words in it.
Here is my declaration:

typedef struct word *word;
Using typedef to create pointers to data objects is dangerous, and
generally poor programming practice. This is despite the fact that
some instructors and books recommend it.
struct word
{
int count;
char *s;
word next;
OK, so this member is actually 'struct word *next'.
};

typedef struct table *table;
As above, dangerous. Likely to cause confusion.
struct table
{
int size;
word *table;
So this member is actually 'struct word **next'.
};
After I fill the table(t) with words, I want to sort it with qsort().
What is the __exact__ definition of 't'?
However, I know my declaration here is wrong somehow:

total(t) gets the total number of words in the table.
here is my call to qsort():

qsort( t->table, total(t), sizeof(word), compare );
I have no idea what you are doing here, or if you are doing what you
think you are doing.

Assuming that 't' is defined as a pointer to a 'struct table', and is
actually initialized to point to a 'struct table', the first value you
are passing to qsort() is 't->table', which has the type 'pointer to a
pointer to a struct word'. So all that this actually points to is a
pointer.
here is my compare() function:

int compare(const void *a, const void *b)
{
word wa = malloc(sizeof(w a));
word wb = malloc(sizeof(w b));
There's a serious problem here, not the least of which is that you
don't free() the memory you allocated, so you are creating a memory
leak. Let's lose the typedef's and see what you are really defining
above:

struct word *wa = malloc(sizeof(s truct word *));
struct word *wb = malloc(sizeof(s truct word *));

You are allocating enough memory for the size of a pointer to a
structure, and assigning it to a pointer to that structure type. Since
the structure contains a pointer to its own type, plus other members,
its size must be greater than the size of the pointer.
wa = *(const word const *) a;
wb = *(const word const *) b;
Let's lose the typedef's here, as well.

wa = *(const struct word * const *) a;
wb = *(const struct word * const *) b;

As near as I can tell, since you haven't shown us the actual
definition of 't', you are copying two structures into allocated
memory that is not large enough to hold them. You have generated
undefined behavior.

if( (wb->count) - (wa->count) == 0 )
{
return( strcmp(wb->s, wa->s) );
}

return ( (wb->count) - (wa->count) );
}

Somehow, wb and wa are not getting the right values. wa seems to get an
actual word but wb is left NULL and i end up with a bus error. Any
advice on this matter would be much appreciated.


The first thing you need to do is get rid of the typedef's. Don't
ever use them for pointers that you will actually be dereferencing,
you are getting lost behind them.

Really, really, REALLY get rid of those typedef's.

Then there is this. The qsort() function sorts arrays, not linked
lists. If you want to sort a linked list, you need a different
algorithm, one that is not provided in the C standard library.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #2
"dough" <vi****@gmail.c om> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
I have a hash table with seperate chaining with a bunch of words in it.
Here is my declaration:

typedef struct word *word;
^^^ I'm not sure it's generally a good idea to have the same name for
different things.
struct word
{
int count;
char *s;
word next;
};

typedef struct table *table;
struct table
{
int size;
word *table;
^^^ now you have 3 things named table. Scary...
And here table seems to be a ptr to a ptr to a struct word according to your
definitions. I'm not sure this is what you want.
};
After I fill the table(t) with words, I want to sort it with qsort().
However, I know my declaration here is wrong somehow:

total(t) gets the total number of words in the table.
here is my call to qsort():

qsort( t->table, total(t), sizeof(word), compare );
sizeof(word) is sizeof(ptr to struct word), so, you're about to sort
pointers?
here is my compare() function:

int compare(const void *a, const void *b)
{
word wa = malloc(sizeof(w a));
word wb = malloc(sizeof(w b));
Ouch. You're allocating as much memory for pointers wa and wb as their own
size... Are you sure the following won't be enough:
word wa, wb;
?
wa = *(const word const *) a;
wb = *(const word const *) b;
Are you sure you need 1st asterisk?
if( (wb->count) - (wa->count) == 0 )
{
Where did you free memory allocated by malloc()? C's not Java...
return( strcmp(wb->s, wa->s) );
}

Where did you free memory allocated by malloc()? C's not Java...
return ( (wb->count) - (wa->count) );
}

Somehow, wb and wa are not getting the right values. wa seems to get an
actual word but wb is left NULL and i end up with a bus error. Any
advice on this matter would be much appreciated.


Your code is very very bad. Maybe because you don't understand what you
wrote (and worse if you don't understand what you want) you can't get it to
work.

Alex
Nov 15 '05 #3
In article <qt************ *************** *****@4ax.com>,
Jack Klein <ja*******@spam cop.net> wrote:
On 2 Oct 2005 21:10:21 -0700, "dough" <vi****@gmail.c om> wrote in
comp.lang.c:
I have a hash table with seperate chaining with a bunch of words in it.
Here is my declaration:

typedef struct word *word;


Using typedef to create pointers to data objects is dangerous, and
generally poor programming practice. This is despite the fact that
some instructors and books recommend it.


Would you detail the dangers? I can only think that it
might make it more likely that some one will evaluate an
invalid pointer.

--
Michael Press
Nov 15 '05 #4
Michael Press wrote:
In article <qt************ *************** *****@4ax.com>,
Jack Klein <ja*******@spam cop.net> wrote:

On 2 Oct 2005 21:10:21 -0700, "dough" <vi****@gmail.c om> wrote in
comp.lang.c :

I have a hash table with seperate chaining with a bunch of words in it.
Here is my declaration:

typedef struct word *word;


Using typedef to create pointers to data objects is dangerous, and
generally poor programming practice. This is despite the fact that
some instructors and books recommend it.


Would you detail the dangers? I can only think that it
might make it more likely that some one will evaluate an
invalid pointer.


Well, try to get a "const struct word*" from the typedef "word".
If you use "const word", you get a "struct word * const".
People not aware of this may run into trouble. Let alone volatile.

Another thing is "forgetting " that one is dealing with a pointer
which is particularly nasty if you work with void * and get
back your objects by cast...

These are just two but I saw enough bugs with a pointer typedef
at the bottom to avoid them for the future. One saved "*" is not
worth it.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4255
by: Pelo GANDO | last post by:
Hi everybody ! I am a beginner in C++. I am looking for a (simple if it's possible) source code in C++ about hash table... Thank you ! Pelo
4
26463
by: john sutor | last post by:
Does anyone know how to sort a hash table?
2
2527
by: Ravi | last post by:
Hi, I am working on a winform app. I need to use an object which can store some information(key/value pairs) and also can be acessed by multiple threads(read/write). From what I heard Hash table is best suited for it. My question is Why hash table. why can't we use an array. I thought hash table uses more memory than array. Correct me if am wrong.
6
7831
by: Fred Morrison | last post by:
Do you know of a way to load a hash table with random key/value pairs (e.g., 2/"Two",1/"One",3/"Three") and then iterate through the entries in "sorted" (key sequence) order (1/"One",2/"Two",3/"Three")? The following just returns them in the order they were loaded: Dim hshPrimaryKeyInfo as New Hashtable <snip code to Add entries to hash table> For Each hshEntry As DictionaryEntry In hshPrimaryKeyInfo
21
3223
by: Johan Tibell | last post by:
I would be grateful if someone had a minute or two to review my hash table implementation. It's not yet commented but hopefully it's short and idiomatic enough to be readable. Some of the code (i.e. the get_hash function) is borrowed from various snippets I found on the net. Thee free function could probably need some love. I have been thinking about having a second linked list of all entries so that the cost of freeing is in proportion to...
139
14216
by: ravi | last post by:
Hi can anybody tell me that which ds will be best suited to implement a hash table in C/C++ thanx. in advanced
0
926
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi have data in a hash table that I copy into an array list. The data is in the form name(string) number(string)-because it can have some letters in it user(string) starttime(datetime) endtime(datetime) I want to sort it by name and then starttime,could you do this from the arraylist?
23
5741
by: raylopez99 | last post by:
A quick sanity check, and I think I am correct, but just to make sure: if you have a bunch of objects that are very much like one another you can uniquely track them simply by using an ArrayList or Array, correct? An example: create the object, create an array, the stuff the object into the array. Later on, assume the object is mutable, the object changes, but you can find it, if you have enough state information to uniquely identify...
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.