2

I am trying to build a hash table, using the following node and table:

typedef struct Node {
   int key;
   int value;
   int status;     
} Node;

typedef struct Table {
   int size;
   Node* node;
} Table;

node in struct Table is a Node pointer so I thought hasht(Table*)->node would be a Node*. I tried to initialize all the node* in the table to NULL like this:

for(int i=0;i<hasht->size;i++)
{
   hasht->node[i]=NULL;
}

However, when I compile the code it give me this error:

" incompatible types when assigning to type ‘Node {aka struct Node}’ from type ‘void *’ hasht->node[i]=NULL; "

I don't understand why hasht->node[i] is a Node, not a Node*. How can I get a Node* member in the Table variable with a Table*?

3 Answers 3

1

hasht->node is a Node *, which can be a pointer to a single Node or a pointer to an array of Node objects. hasht->node[i] then refers to the ith Node object in such an array. Note that by definition, for a pointer p, p[i] is equivalent to *(p + i).

If you want your table to have an array of nodes, you can use it as-is, but then there's nothing to null out, because there are actual Node objects in the table.

If, on the other hand, you want an array of pointers to nodes for some reason, you'll need to change the table member to Node **node. Then, you can have it point to an array of pointers to Node, which can indeed be nulled out individually (since hasht->node[i] would be a Node * then). You'll get memory fragmentation and be cache-unfriendly, though.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure you want to initialize struct pointer to NULL?

I tried to initialize all the node* in the table to NULL like this:

There is only one pointer and I suppose you need to allocate some memory for it:

hasht->node = calloc(hasht->size, sizeof(Node));

Comments

0

Your index is in the wrong place. You need

hasht[i]->node=NULL; (and not hasht->node[i]=NULL;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.