I want to ‘construct’ (read: malloc and memset) my hashtable in c. To do this, I created a function as follows:
int maketable(struct hash_entry **table, int size){
table = (struct hash_entry **)malloc(size*sizeof(struct hash_entry *));
int i = 0;
for (; i<size; i++) {
memset(table[i], '\0', sizeof(struct hash_entry *));
}
return 0;
}
Given that table will have been declared as
struct hash_entry **table[size]
before entering this code, I won’t lose anything when I return from maketable, right?
EDIT:
Does passing table into maketable() ensure that as long as I change the data that table points to, the changes will be preserved?
EDIT II:
I am trying to allocate an array of pointers to pointers to hash_entries
Your code is assigning to the local
tablevariable, the caller is not affected. This results in a memory leak.Outside the function, you have declared table as an array of pointer to pointers of struct hash_entry – I’m guessing you rather just want an array of pointers to struct hash entries.
If you actually declare
tableas an array, there’s no need to malloc that space. You just need a loop to set every element in it to NULL (Don’t memset each element to zeroes).If the goal is to allocate the entire table, this is perhps what you’re looking for:
call it like
I’d rather make that return the table like so:
if the declaration
struct hash_entry **table[size]is really what you want, you need to tell us what your maketable() function actually is supposed to do (e.g. do you want to a dynamically allocated ‘array’ as one of the elements in that table ?