【发布时间】:2019-04-28 23:12:57
【问题描述】:
在 C 中动态分配结构数组及其组件的正确方法是什么?我已经设法做了一些有效的事情,但我有点怀疑它是否正确。
我有以下代码:
这是我需要动态分配的结构数组:
typedef struct
{
char *wrong;
char *right;
}Dictionary;
这是我需要初始化结构数组时调用的函数:
Dictionary *init_Dictionary(int nr_elem)
{
Dictionary *dict;
dict = malloc(nr_elem*sizeof(Dictionary));
for(int i=0; i<nr_elem; i++)
{
char wrong[101],right[101];
scanf("%s%s",wrong,right);
dict[i].wrong = malloc(strlen(wrong)*sizeof(char));
dict[i].right = malloc(strlen(right)*sizeof(char));
strcpy(dict[i].wrong,wrong);
strcpy(dict[i].right,right);
}
return dict;
}
然后在我的主要功能中,我有这个:
int nr_elem;
scanf("%d",&nr_elem);
Dictionary *dict;
dict = init_Dictionary(nr_elem);
另外,当我完成结构的工作后,如何释放使用的内存?
编辑感谢大家快速而深入的回答!
【问题讨论】:
-
dict[i].wrong = malloc(strlen(wrong)*sizeof(char));->dict[i].wrong = malloc(strlen(wrong) + 1);(你需要一个额外的字符作为字符串终止符,sizeof(char)是多余的)。 -
不要忘记 C 中的
char字符串实际上称为 null-terminated 字节字符串,并且 null-终结者也需要空间,并且不被strlen计算。 -
你需要将每个
malloc(或类似的)与free匹配。 -
@Someprogrammerdude 所以我必须遍历我的结构数组并在结构的每个组件上免费调用?
-
是的,在循环
free之后也是结构的“数组”。
标签: c arrays struct dynamic-memory-allocation