0

I would like to know how to declare, allocate and initialize array of Node to null.

typedef struct Nodes_Of_List { 
        int data; 
        struct Nodes_Of_List *next;
} Node;

//declare array of head nodes
Node *table;

//ALOCATE memory for "x" x is provided at runtime, number of head nodes
table = malloc(sizeof(Node) * x); 

//Initialize elements to Null value
?? //How to do it 

Explanation regarding initializing dynamic array of head nodes of linked list to Null requested. Purpose is to make array of linked lists, to make a hashtable.

7
  • 1
    It's unclear what you're trying to do. Do you have a single list, or a list of lists? Commented Jul 10, 2020 at 13:30
  • 1
    Is a Node what you mean by a head node? Or do you need another structure such as typedef struct Head_Node { Node *head; Node *tail; } Head_Node;? (Note that the 'tags' namespace is separate from the ordinary identifiers namespace, so struct Head_Node does not conflict with Head_Node.) You define an array of whatever type it is the same way as you define an array of int — except you use a different type name. If x is a variable rather than a constant, you use malloc() to allocate the memory. Using calloc() will (de facto if not de jure) initialize the allocated memory to null. Commented Jul 10, 2020 at 13:43
  • This link can help you a lot: stackoverflow.com/questions/46320526/… If you need more details, please elaborate on the comments(or edit question) so we can help. Commented Jul 10, 2020 at 14:46
  • You can initialize with table->data = NULL; table->next = NULL; Commented Jul 10, 2020 at 17:29
  • @Lucas: since the data element is an int, it would be best not to use NULL but just 0 to initialize it. Commented Jul 10, 2020 at 20:43

1 Answer 1

1

Based on what I understood, you want to declare an array of head nodes. After that, you want to initialize them to NULL:

//declare array of head nodes statically
Node * table[x];      // x value provided at runtime
// Or dynamically
Node ** table = (Node **) malloc(sizeof(Node *) * x);
// Or use calloc directly wich will initialize your pointers to 0
Node ** table = (Node **) calloc(x, sizeof(Node *));

// table is an array of pointers. Each pointer references a linked list.
// Now you have just to put NULL value in each element of table
int i;
for(i = 0; i < x; i++) 
    table[i] = 0;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.