On Mon, 16 Aug 2004, Pieter Claassen wrote:
>
> Here is a test program that compiles and works
No, it doesn't. First, there's the non-standard header file
<search.h>, and then there are calls to undeclared functions such
as 'hcreate' and 'hsearch', and undefined types such as 'ENTRY'.
No wonder it has problems! Try posting a complete, compilable
program, or if this <search.h> is some platform-specific header,
try asking a newsgroup dedicated to your platform.
When you post code to Usenet, do not use hard tabs (ASCII 0x09).
They ruin the indentation and make it hard to read or quote properly.
Run the program through a detabber such as <blatant plug>
http://www.contrib.andrew.cmu.edu/~a...e/usenetify2.c
before posting.
Code reflowed for readability below...
> typedef struct {
> char *name;
> char *data;
> } pkt;
>
> void get_state(const pkt *a, pkt *b);
>
> int main()
> {
> pkt d, r;
> hcreate(100);
>
> d.name = "A";
> d.data = "B";
> get_state(&d, &r);
Here you are entering ("A", ("A","B")) into the hash.
> printf("data val is %s\n", r.data);
This prints "data val is B".
> d.name = "A";
> d.data = "b";
Here you are overwriting the "B" with a "b": now ("A", ("A","b"))
is in the hash, and ("A", ("A","B")) is not. If you don't understand
this, I recommend you start with standard C, and study pointers.
Work your way up to complicated things like hashtables. Even if you
already know one language, it can be tricky to apply that knowledge
to another language as dissimilar as C.
> get_state(&d, &r);
Here you are trying to insert ("A", ("A", "b")) into the table.
I can't tell, from the meager documentation I found via Google, what
this will do.
> printf("data val is %s\n", r.data);
This will either print "data val is b", or it will print nothing,
the program having already crashed (or worse) upon trying to dereference
the null pointer returned by 'hsearch'.
> hdestroy();
> return 0;
> }
>
>
> void get_state(const pkt *a, pkt *b)
> {
> ENTRY e, *t;
>
> e.key = a->name;
> e.data = (void*)a;
> t = hsearch(e, ENTER);
> memcpy(b, t->data, sizeof *b);
> }
> Questions:
> 1. This only works if I memcpy the data to a statically(?) allocated
> struct (r). Why can I not just do the following in get_state:
>
> t = hsearch(e,ENTER);
> b = (pkt*)t->data;
>
> When I do this, it is as if the data that t is pointing to is cleaned
> up and b then points to garbage.
As I said, study pointers for a while. Changing the value of the
local variable 'b' inside 'get_state' doesn't do anything to 'r' back
in 'main'. So indeed 'r' continues to hold (not "point to") garbage.
I recommend K&R2, "The C Programming Language." If you're doing
hash-tables already, you probably have enough experience to understand
their style of exposition.
HTH,
-Arthur