【发布时间】:2012-04-06 05:49:04
【问题描述】:
我试图了解 Freebsd 中 queue (3) 宏的内部工作原理。我曾就同一主题向之前的question 提问过,这是一个后续问题。
我正在尝试定义一个将元素插入队列的函数。 queue (3) 提供了宏 STAILQ_INSERT_HEAD,它需要一个指向队列头部的指针、队列中项目的类型以及要插入的项目。我的问题是我得到了
stailq.c:31: warning: passing argument 1 of 'addelement' from incompatible pointer type
当我尝试将head 的地址传递给函数时出错。完整源代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
struct stailq_entry {
int value;
STAILQ_ENTRY(stailq_entry) entries;
};
STAILQ_HEAD(stailhead, stailq_entry);
int addelement(struct stailhead *h1, int e){
struct stailq_entry *n1;
n1 = malloc(sizeof(struct stailq_entry));
n1->value = e;
STAILQ_INSERT_HEAD(h1, n1, entries);
return (0);
}
int main(void)
{
STAILQ_HEAD(stailhead, stailq_entry) head = STAILQ_HEAD_INITIALIZER(head);
struct stailq_entry *n1;
unsigned i;
STAILQ_INIT(&head); /* Initialize the queue. */
for (i=0;i<10;i++){
addelement(&head, i);
}
n1 = NULL;
while (!STAILQ_EMPTY(&head)) {
n1 = STAILQ_LAST(&head, stailq_entry, entries);
STAILQ_REMOVE(&head, n1, stailq_entry, entries);
printf ("n2: %d\n", n1->value);
free(n1);
}
return (0);
}
据我所知,head 是 struct stailhead 类型,addelement 函数还需要一个指向 struct stailhead 的指针。
STAILQ_HEAD(stailhead, stailq_entry); 扩展为:
struct stailhead {
struct stailq_entry *stqh_first;
struct stailq_entry **stqh_last;
};
我在这里错过了什么?
谢谢。
【问题讨论】:
-
这可能与您两次调用 STAILQ_HEAD 宏的事实有关,从而重新定义了结构。不要那样做。只需将 head 声明为所需类型的结构(即“struct stailhead head;”)。这些宏不是没有命名空间副作用的。
标签: c