-1

I have 2 structures in my C code. I want to write a hash function with these 2 structures. So I want to initialize my data null in first case. My code is

struct HashNode
{
    char username[20];
    char password[20];

};

struct HashTable
{
    int size;
    struct HashNode *table;
};

HashTable *initializeTable(int size)
{

    HashTable *htable;

    if (size < MIN_TABLE_SIZE)
    {
        printf("Table Size Small\n");
        return NULL;
    }
    htable = (HashTable *)malloc(sizeof(Hashtable));

    if (htable == NULL)
    {
        printf("memory allocation pblm\n");
        return NULL;
    }
    htable->size = size;
}

How can I allocate memory for htable->table with that size? I have code in C++ like htable->table = new HashNode [htable->size];. How can I write this in C using malloc?

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
user39320
  • 61
  • 5
  • 1
    `malloc(size * sizeof *(htable->table))` seems like a good bet. And if this is C, [stop casting `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Apr 30 '15 at 06:39
  • i have one doubt . Is memory automatically allocated for "struct HashNode" when i call htable = (HashTable *)malloc(sizeof(Hashtable)); ?? because the pointer inside that structure . – user39320 Apr 30 '15 at 06:43
  • @user39320 No. Your first `malloc` allocates space for a `HashTable` structure, which includes one `int` and one data pointer (plus padding depending on the implementation). After that call both `htable->size` and `htable->table` are *indeterminate*. That is why there are two `malloc` calls. Though it is possible to do this with a single `malloc` via some fancy calculations and some pointer math, or a language feature called a *flexible array member*, rare is a time it is warranted, and this isn't one of those times. – WhozCraig Apr 30 '15 at 06:48

1 Answers1

0

You can allocate the memory in this way

htable->table = malloc(size*sizeof(HashNode))
prince
  • 1,129
  • 1
  • 15
  • 38