No. Your types don't match up.
Are you trying to allocate a table of hash entries (i.e., the type of table[i]
is struct hash_entry
), a table of pointers to hash_entries (i.e., the type of table[i]
is struct hash_entry *
), or something else? Based on how your code reads, I'm assuming the first case, but let me know if that's wrong.
Assuming you're dynamically allocating a table of struct hash_entry
, your declaration of the table in the caller should be
struct hash_entry *table; // 1 *, no array dimension
the function should be called as
int result = maketable(&table, number_of_elements);
and defined as
int maketable (struct hash_entry **table, size_t size)
{
int r = 0;
// sizeof **table == sizeof (struct hash_entry)
*table = malloc(sizeof **table * size);
// *ALWAYS* check the result of malloc()
if (*table)
{
size_t i;
for (i = 0; i < size; i++)
memset(&(*table)[i], 0, sizeof (*table)[i]);
r = 1;
}
return r;
}
A couple of things to point out. First of all, don't cast the result of malloc()
. As of C89, you don't need to, and the cast will supress a diagnostic if you forget to include stdlib.h or otherwise don't have a prototype for malloc()
in scope. Secondly, you can use the sizeof
operator on objects instead of types. This can help reduce some maintenance headaches (i.e., if you change the type of table
in the parameter list, you don't have to change the sizeof
calls along with it).
Finally, note that the address of table is being passed to the function; since we're trying to write to a pointer value, we must pass a pointer to that pointer.
If you were attempting to create a table of pointers to struct hash_entry
, the code is mostly the same, just an extra level of indirection:
your declaration of the table in the caller should be
struct hash_entry **table; // 2 *, no array dimension
the function should be called as
int result = maketable(&table, number_of_elements);
and defined as
int maketable (struct hash_entry ***table, size_t size)
{
int r = 0;
// sizeof **table == sizeof (struct hash_entry *)
*table = malloc(sizeof **table * size);
// *ALWAYS* check the result of malloc()
if (*table)
{
size_t i;
for (i = 0; i < size; i++)
(*table)[i] = NULL;
r = 1;
}
return r;
}
EDIT There was a bug in the maketable
examples; table
needs to be dereferenced before applying the subscript, i.e., (*table)[i]
. We're applying the subscript to what table
points to, not the table pointer itself.
Sorry for any confusion.