如何在C中释放结构体数组
我有一个像这样的结构数组
typedef struct {
char *name[50];
int score;
} score;
内存被分配给该数组,就像这样
score *scores = (score *) malloc(sizeof(score) * size);
我需要进行 if 检查,并且关于该检查我正在释放该内存空间。所以现在,我脑子里有两个问题:
- 为什么我不能像这样释放空间?
for (int i = 0; i < size; i++) {
if (scores[i].score == scoreToBeDeleted) {
free(scores[i].name);
free(&(scores[i].score));
free(&(scores[i]));
}
}
- 删除记录时是否应该移动数组的元素?
I have a struct array like this
typedef struct {
char *name[50];
int score;
} score;
Memory is allocated to that array like this
score *scores = (score *) malloc(sizeof(score) * size);
I need to do an if-check and regarding to that check I am deallocating that memory space. So right now, I have 2 questions in my mind
- Why can't I just free-up space like this ?
for (int i = 0; i < size; i++) {
if (scores[i].score == scoreToBeDeleted) {
free(scores[i].name);
free(&(scores[i].score));
free(&(scores[i]));
}
}
- Should I shift the elements of the array as I remove records ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法取消分配结构变量,因为您没有显式分配它们,而是分配了结构分数数组。
这样你就可以实现你想要的行为。或者您可以使用分数链接列表。
You can't deallocate your struct variables because you haven't allocated them explicitly, you have allocated the array of struct scores.
This way you can achieve your desired behavior. Or you could use linked list of scores.