简体   繁体   English

为C中的结构数组声明并分配内存

[英]Declare and allocate memory for an array of structures in C

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. MAX_STRchar word选择器的最大大小。 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. 我计划能够将其引用为: final_list[i].count它将是整数)和final_list[i].word (将是字符串)。

i being an integer variable. i是一个整数变量。

However, such expressions always return (null) . 但是,此类表达式始终返回(null) I know I'm doing something wrong, but I don't know what. 我知道我做错了,但是我不知道该怎么办。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

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. 指针本身的内存已通过calloc正确分配,但这只是一个地址。

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. 这还需要释放struct本身的数组之前释放final_list[i].word指向的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM