C 从结构队列中删除所有节点
我正在尝试从结构队列中删除所有节点 结构:C 从结构队列中删除所有节点,c,structure,free,C,Structure,Free,我正在尝试从结构队列中删除所有节点 结构: struct element{ int id; int sign; int year; int month; double amount; struct element *next; }; struct queue{ struct element *head; int size; }; 我写的函数是: void delete(struct queue *queue) {
struct element{
int id;
int sign;
int year;
int month;
double amount;
struct element *next;
};
struct queue{
struct element *head;
int size;
};
我写的函数是:
void delete(struct queue *queue) {
if (queue->size == 0){
printf("Structure is empty\n");
}
else {
struct element* this;
struct element* other;
for(this=queue->head;this!=NULL;this=other)
{
other=this->next;
free(this);
}
free(queue);
}
}
这不管用,我也没有主意了。有什么建议吗?在
删除
例程中,如果大小为空,则不会释放队列
,但如果大小为非空,则会释放队列。对于这两种情况,您可能都应该这样做。也就是说,不是两个地方都免费,就是两个地方都免费
因为delete
无法知道队列是如何分配的,所以需要弄清楚应该做什么是很麻烦的。考虑到您当前的设计,一种解决方法可能是向delete
传递一个标志,以指示它应该做什么:
void delete(struct queue *queue, int do_free) {
if (queue->size == 0){
printf("Structure is empty\n");
}
else {
struct element* this;
struct element* other;
for(this=queue->head;this!=NULL;this=other) {
other=this->next;
free(this);
}
queue->head = 0;
queue->size = 0;
}
if (do_free) free(queue);
}
struct queue new;
/* ... */
delete(&new, 0); /* don't free the queue */
struct queue *empty_new = malloc(sizeof(struct queue));
empty_new->size = 0;
delete(empty_new, 1); /* free the empty queue */
传递队列的第一个元素怎么样
void delete(element *el ) {
if(el) {
delete(el->next );
free(el);
}
}
与
这里
new
是在堆栈上分配的,所以不要在delete
中调用free(queue)
。
相反,设置queue->head=NULL;队列->大小=0
表示队列现在为空,如@kirill所述。您可能忘记了在函数末尾更新指向NULL的指针以及将队列大小更改为0 会发生什么?你有错误吗?我能看到的一件事是关于你有多少元素的信息是多余的。队列中有size
,但队列中最后一个元素中的next
也有一个空指针。你确定那些总是匹配的吗?我的意思是,如果遍历列表,是否可以保证在命中NULL之前运行size
元素?@MrLister当我尝试使用此函数时,Netbeans会将其中断(收到的信号:SIGABRT(中止))。没有具体说明,但在哪一行中止?您能否调试程序和/或插入一些诊断printf语句?如何调用delete
?我怀疑,队列没有在堆上分配。如果它是空的,我为什么要释放它(假设我理解你的观点)?@ozech:我会用一个问题来回答:你为什么要在清空它之后再释放它?把它从堆栈中清除completely@ozech:您只能释放malloc
或calloc
或realloc
返回的内存。堆栈上的空队列占用的内存与堆栈上的空队列占用的内存一样多。我应该调用free(&queue)
而不是?@ozech-否,如果它在堆栈上的分配与我回答中的代码一样,它将自动释放。
typedef struct _element{
int id;
int sign;
int year;
int month;
double amount;
struct _element *next;
} element;
struct queue new;
//...
delete(&new);