如何释放结构数组的malloc

问题描述 投票:0回答:1

我一直在研究一个使用结构作为字符串存储的项目。我声明了一个由char类型成员组成的结构:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

[我知道我可以执行char *name, char *address...,但是假设我们指定的最大长度为50。然后在使用该结构的函数上,我以30的索引大小对其进行了分配:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

应该通过访问每个索引完成将所有字符串复制到结构中,如何释放调用malloc之后使用的已分配内存?我尝试在程序结尾处执行free(dsdata),但不确定是否正确。我应该单独释放每个索引吗?请赐教。预先感谢您的反馈!

c struct malloc free
1个回答
0
投票

据我所知,您仅使用mallocdatastore1结构的数组分配空间,因此只需执行free(dsdata)就足够了。

如果在结构中您将拥有指针,并且将使用malloc来分配每个指针,则只比您首先需要free分配每个指针。

© www.soinside.com 2019 - 2024. All rights reserved.