我正在使用malloc()
函数在 C 中创建队列,问题是当我使用 dequeue()
函数时,我留下了一个未引用的元素。我必须每秒多次使用此功能,所以我想知道哪种是处理它的最佳方法,或者是否有比使用 malloc()
更好的方法。这是两个函数:
void enqueue(struct Queue *q, char c){
//adds an element to the queue
struct Member* m = malloc(sizeof *m);//in order to make m global
if(!m){ perror("malloc");exit(EXIT_FAILURE);}
if(q->length == 0){
m->ch = c;
q->first = m;
q->last = m;
}else{
m->ch = c;
q->last->next = m;
q->last = m;
}
q->length++;
}
char dequeue(struct Queue *q){
//returns the first element of the queue an delete it
char c;
if(q->length >0){
q->length--;
c = q->first->ch;
q->first= q->first->next;
//CLEAR THE UNREFERENCED VARIABLE
}
return c;
}
谢谢!
编辑:
这些是我正在使用的结构:
typedef struct Queue{
int length;
struct Member *first;
struct Member *last;
}Queue;
typedef struct Member{
char ch;
struct Member *next;
}Member;
首先将unreferenced variable
存储到temporary variable
,以便在更改队列的第一个节点后可以free
它。
//returns the first element of the queue and delete it
char dequeue(struct Queue *q){
struct Member* temp = q->first;;
char c;
if(q->length >0){
q->length--;
c = q->first->ch;
q->first= q->first->next;
free(temp);
}
return c;
}
您可以在此处查看有关free
的更多信息。