Reputation:
I'm trying to declare and allocate memory for an array of structures defined as follows:
typedef struct y{
int count;
char *word;
} hstruct
What I have right now is:
hstruct *final_list;
final_list = calloc (MAX_STR, sizeof(hstruct));
MAX_STR
being the max size of the char word
selector.
I plan on being able to refer to the it as:
final_list[i].count
, which would be an integer and
final_list[i].word
, which would be a string.
i
being an integer variable.
However, such expressions always return (null)
. I know I'm doing something wrong, but I don't know what. Any help would be appreciated. Thanks.
Upvotes: 1
Views: 561
Reputation: 133639
A struct that contains a pointer doesn't directly holds the data, but holds a pointer to the data. The memory for the pointer itself is correctly allocated through your calloc
but it is just an address.
This means that is your duty to allocate it:
hstruct *final_list;
final_list = calloc(LIST_LENGTH, sizeof(hstruct));
for (int i = 0; i < LIST_LENGTH; ++i)
final_list[i].word = calloc(MAX_STR, sizeof(char));
This requires also to free the memory pointed by final_list[i].word
before releasing the array of struct itself.
Upvotes: 1