-1

I need to initialized the hash table with the size i get, i have a problem here t->arr_table[i]->key = NULL;

#include <stdio.h>

typedef struct element{
    char * key;      
    char * value;    
}element;

typedef struct HashTable{
    int size;    // size of the arr
    element **arr_table;   //arr of elements
}HashTable;


void init_hash(int size, HashTable * t)
{
    if (size < 1)
        return;
    t->size = size;
    t->arr_table = (element **)malloc(sizeof(element*)*size);
    if (t->arr_table == NULL) // out memory
        return;
    int i;
    for (i = 0; i < size; i++)
    { // initial list
        t->arr_table[i]->key = NULL;
        t->arr_table[i]->value = NULL;
    }

}



void main()
{
    HashTable *ht = (HashTable*)malloc(1*sizeof(HashTable));
    int size_ht = 9;
    init_hash(size_ht, ht);
    printf("...\n");
    return;
}
edenv3
  • 9
  • 5
  • "I have a problem". Don't you think it would make sense to tell us what the problem is exactly? Isn't that common sense? – kaylum Jan 16 '17 at 21:52
  • Because i don't know why it is happaned @kaylum – edenv3 Jan 16 '17 at 21:56
  • Are you trying to create an ***array of pointers to elements*** or an ***array of elements*** inside the `HashTable` structure? – user3386109 Jan 16 '17 at 21:56
  • Why *what* happened?? You haven't actually told us what bad behaviour you have observed. You must have observed something that is causing you problems. What is that *something*? – kaylum Jan 16 '17 at 21:57
  • I try to create a array of elements inside HashTable @user3386109 – edenv3 Jan 16 '17 at 21:57

1 Answers1

1

What you've made is an array of pointers to elements. However, the init_hash function seems to expect an array of elements. To create an array of elements the code should be as shown below. I've added some comments to highlight some of the changes.

typedef struct element{
    char *key;
    char *value;
}element;

typedef struct HashTable{
    int size;
    element *arr_table;     // <-- only one '*', not two, to declare a pointer to an array of elements
}HashTable;

void init_hash(int size, HashTable *t)
{
    if (size < 1)
        return;
    t->size = size;
    t->arr_table = malloc(sizeof(element) * size);  // <-- allocate memory for the elements, note 'sizeof(element)' not 'sizeof(element *)'
    if (t->arr_table == NULL)
        return;
    int i;
    for (i = 0; i < size; i++)
    {
        t->arr_table[i].key = NULL;         // <-- table[i] is a structure, use dot notation
        t->arr_table[i].value = NULL;
    }
}

int main( void )    // <-- declare main with the correct signature
{
    HashTable *ht = malloc(sizeof(HashTable));  // <-- don't cast the return value from malloc
    int size_ht = 9;
    init_hash(size_ht, ht);
    printf("...\n");
}
user3386109
  • 34,287
  • 7
  • 49
  • 68