FlamePrinz
FlamePrinz

Reputation: 490

How do I use a self referential struct definition (in C)?

Here is my situation. I have a hash-table and a node as my structures. The nodes have pointers to other nodes (a linked-list), and the hash-table is an array of nodes. I define the two structures as:

typedef struct node{
    char* hashStr;
    struct node* nextNode;
}node;

typedef struct hashTable{
   int emptyNodes[16];
   node* pods[16];
}hashTable;

I have defined the maximum amount of nodes in a linked-list as 32. Whenever I add a node to the linked-list, I check if the linked-list is of length 32. If the length is 32, and I want to add another node, I want to delete the first node in the linked-list, and add the new node to the back, like a FIFO queue.

My issue is in deleting the first node. Instead of deleting the first node, I think the most reasonable thing is to have the node pointer in the hashTable (that is at some key (since it is an array of node pointers)), simply point to the next node which is referred to as nextNode in the node struct. I can't do this though because nextNode is NOT a struct.

I tried this:

(*addr).pods[key] = (*addr).pods[key].nextNode;

I get the error:

error: request for member 'nextNode' in something not a structure or union

I understand the error, but I'm not sure how to fix it. I found this on stackoverflow, but I'm not sure how to apply it to my work (if I even can):

Why do I get "request for member in something not a struct or union" from this code?

Upvotes: 0

Views: 115

Answers (3)

Achal
Achal

Reputation: 11921

Here

node* pods[16];

pods[key] is of node* type. While accessing nextNode using pods[key] use arrow -> operator. For e.g

(*addr).pods[key]->nextNode

Upvotes: 1

gsamaras
gsamaras

Reputation: 73366

Change this:

(*addr).pods[key].nextNode;

to this:

(*addr).pods[key]->nextNode;

since pods[key] is of type node*, i.e. a pointer to a node.

Upvotes: 1

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

(*addr).pods[key] = (*addr).pods[key]->nextNode;

The pods is an array of pointers. Once you have the pointer, you need to dereference it to access the underlying object.

Upvotes: 2

Related Questions