1

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_STRbeing 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.

ibeing 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.

2
  • Are you initializing the counts or words anywhere?
    – A.E. Drew
    May 14, 2013 at 3:25
  • 1
    You are confused about how calloc works. The first argument should be the number of elements u will have in the hstruct array. May 14, 2013 at 3:41

1 Answer 1

1

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.