1

I have found some code that I need to use for my application but there are two lines in it I can't figure out what exactly do they do and how... Please, either explain them to me or direct me to a link so I can read more about it.

Dict* dcreate(hash_size size, hash_size (*hashfunc) (const char *)); 

Here I guess it is passing a function as a parameter with it's parameter in the following bracket!?

hash_size i = dict->hashfunc(key) % dict->size; 

and here, my guess is as good as my dog's!

The hashfunc:

static hash_size def_hashfunc(const char* key){ hash_size s = 0; while(*key){ s += (unsigned char) *key++; } return s; } 

Thanks.

1
  • 1
    What they said. Also, you have "hash" in your tags, but it doesn't matter what the functions do; this mechanism is the same for non-hash-related functions! Commented Dec 26, 2011 at 9:15

4 Answers 4

3

For the first line, your guess is correct. That is the header for a function that accepts two arguments, one of which is of the hash_size type, and another which is a pointer to a function whose argument is a const char* and returns a hash_size.

In the second line, dict appears to be a pointer to a struct, so dict->hashfunc(key) calls the function hashfunc, a pointer to which is stored in the dict struct. The last part (... % dict->size) is just the modulo operation.

Sign up to request clarification or add additional context in comments.

Comments

3
hash_size (*hashfunc) (const char *) 

Is a Function Pointer.

hashfunc is a pointer to a function which receives a const char * as an argument and returns a type hash_size.

Comments

1

It only passes a function pointer as a parameter. The following is the definition of the function type that should be passed:

hash_size (*hashfunc) (const char *) 

E.g. a function that receives a const char * and returns hash_size.

Comments

1

It is a function pointer

hash_size (*hashfunc) (const char *) 

So that dcreate() will allocate an Dict and fill its field hashfunc like:

Dict * dict = (Dict *) malloc(sizeof(Dict)); dict->hashfunc = hashfunc; 

Then you may call dict->hasfunc(const char *), it will return hash_size.

hash_size i = dict->hashfunc(key) % dict->size; 

It is indeed:

hash_size i = ( dict->hashfunc(key) ) % ( dict->size ) ; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.