How can I declare and initialize an array of pointers to a structure in C?

Posted by worlds-apart89 on Stack Overflow See other posts from Stack Overflow or by worlds-apart89
Published on 2010-04-15T01:14:55Z Indexed on 2010/04/15 1:33 UTC
Read the original article Hit count: 287

Filed under:
|
|
|
|

I have a small assignment in C. I am trying to create an array of pointers to a structure. My question is how can I initialize each pointer to NULL? Also, after I allocate memory for a member of the array, I can not assign values to the structure to which the array element points.

#include <stdio.h>
#include <stdlib.h>

typedef struct list_node list_node_t;

struct list_node
{
   char *key;
   int value;
   list_node_t *next;
};


int main()
{

   list_node_t *ptr = (list_node_t*) malloc(sizeof(list_node_t));

   ptr->key = "Hello There";
   ptr->value = 1;
   ptr->next = NULL;

   // Above works fine

   // Below is erroneous 

   list_node_t **array[10] = {NULL};      

   *array[0] =  (list_node_t*) malloc(sizeof(list_node_t));
    array[0]->key = "Hello world!";  //request for member ‘key’ in something not a structure or union
    array[0]->value = 22;            //request for member ‘value’ in something not a structure or union 
    array[0]->next = NULL;           //request for member ‘next’ in something not a structure or union


    // Do something with the data at hand
    // Deallocate memory using function free 

   return 0;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about structure