Declare and allocate memory for an array of structures in C -
i'm trying declare , allocate memory array of structures defined follows:
typedef struct y{ int count; char *word; } hstruct
what have right is:
hstruct *final_list; final_list = calloc (max_str, sizeof(hstruct));
max_str
being max size of char word
selector. plan on being able refer as: final_list[i].count
, integer , final_list[i].word
, string.
i
being integer variable.
however, such expressions return (null)
. know i'm doing wrong, don't know what. appreciated. thanks.
a struct contains pointer doesn't directly holds data, holds pointer data. memory pointer correctly allocated through calloc
address.
this means duty allocate it:
hstruct *final_list; final_list = calloc(list_length, sizeof(hstruct)); (int = 0; < list_length; ++i) final_list[i].word = calloc(max_str, sizeof(char));
this requires free memory pointed final_list[i].word
before releasing array of struct itself.
Comments
Post a Comment