0

As far as nested functions go, I'm having trouble understanding what the input and outputs for unsigned long int(*hash)(char *); are... Is this nested function taking in a string and outputting a pointer to an unsigned long int?

Thank you!

struct hash_table {
  unsigned long int(*hash)(char *);
  unsigned int n_buckets;
  sll **buckets; /* an array of pointers to string lists */
};
Leeho Lim
  • 19
  • 5

2 Answers2

1
unsigned long int(*hash)(char *);

is a function pointer .

How function pointers work

Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • thank you. And if I wanted to malloc this pointer to the heap, how much memory should I allocate to accommodate for this? – Leeho Lim Feb 19 '15 at 08:08
  • 1
    @Leeho Lim Just in case: are you sure you want to allocate **pointer**? I mean if you have a `struct hash_table variable;`, you already have the pointer inside the variable. The only thing left to do is to assign some appropriate function address to that pointer. – Igor S.K. Feb 19 '15 at 08:23
0

The hash member in the structure is not a nested function, it's a function pointer.

A function pointer is simply a pointer to a function (as the name implies). Since all you can do with functions in C is to call them or take their address, you never need to allocate memory for the function itself.

You can just initialize it with the address of a suitable function, which might look like:

static unsigned long int my_hash(char *s)
{
  return (unsigned long int) *s; /* Very bad hashing! */
}

Then elsewhere:

struct hash_table ht;
ht.hash = my_hash;

Note that the & (address of) operator isn't needed, since there are no parentheses after the name my_hash, the name of the function evaluates to its address.

unwind
  • 391,730
  • 64
  • 469
  • 606