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.

4

1 回答 1

1

包含指针的结构不直接保存数据,而是保存指向数据的指针。指针本身的内存是通过您正确分配的,calloc但它只是一个地址。

这意味着您有责任分配它:

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));

这还需要final_list[i].word在释放结构本身的数组之前释放指向的内存。

于 2013-05-14T03:26:12.730 回答