c - Removing all nodes from a queue of structures -


i'm trying delete nodes queue of structures.

structure:

struct element{ int id; int sign; int year; int month; double amount; struct element *next; }; struct queue{ struct element *head; int size; }; 

and function wrote:

void delete(struct queue *queue) { if (queue->size == 0){ printf("structure empty\n"); } else { struct element* this; struct element* other; for(this=queue->head;this!=null;this=other) { other=this->next; free(this); } free(queue); } } 

it doesn't work, , i'm out of ideas. suggestions?

in delete routine, not free queue if size empty, free if size non-empty. should same both cases. is, either don't free in both places, or free in both places.

it bothersome need figure out right thing is, because delete can not know how queue allocated. given current design, way out may pass flag delete indicate should do:

void delete(struct queue *queue, int do_free) { if (queue->size == 0){ printf("structure 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 queue */ struct queue *empty_new = malloc(sizeof(struct queue)); empty_new->size = 0; delete(empty_new, 1); /* free empty queue */ 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -