[問題] 如何使用 LIST_FOREACH_SAFE ?
開發平台(Platform):
Ubuntu 12.04 amd64
gcc
arm-linux-gnueabi-gcc
額外使用到的函數庫(Library Used):
FreeBSD library
問題(Question):
我在使用FreeBSD linked-list library
照著範例練習
但使用 LIST_FOREACH_SAFE 後編譯錯誤
範例: http://www.unix.com/man-page/FreeBSD/3/LIST_FOREACH_SAFE/
錯誤結果(Wrong Output):
test.c:39: error: ‘entries’ undeclared (first use in this function)
test.c:39: error: (Each undeclared identifier is reported only once
test.c:39: error: for each function it appears in.)
test.c:39: error: expected ‘;’ before ‘{’ token
程式碼(Code):
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sys/queue.h>
4
5 int main()
6 {
7 LIST_HEAD(listhead, entry) head =
8 LIST_HEAD_INITIALIZER(head);
9 struct listhead *headp; /* List head. */
10 struct entry {
11 int a;
12 LIST_ENTRY(entry) entries; /* List. */
13 } *n1, *n2, *n3, *np, *np_temp;
14
15 LIST_INIT(&head); /* Initialize the list. */
16
17 n1 = malloc(sizeof(struct entry)); /* Insert at the head. */
18 n1->a = 7;
19 LIST_INSERT_HEAD(&head, n1, entries);
20
21 n2 = malloc(sizeof(struct entry)); /* Insert after. */
22 n2->a = 5;
23 LIST_INSERT_AFTER(n1, n2, entries);
24
25 n3 = malloc(sizeof(struct entry)); /* Insert before. */
26 n3->a = 1;
27 LIST_INSERT_BEFORE(n2, n3, entries);
28
29 LIST_REMOVE(n2, entries); /* Deletion. */
30 free(n2);
31
32 /* Forward traversal. */
33 //LIST_FOREACH(np, &head, entries) {
34 // printf("%d\n", np->a);
35 //}
36
37
38 /* Safe forward traversal. */
39 LIST_FOREACH_SAFE(np, &head, entries, np_temp) {
40 // do somethings
41 LIST_REMOVE(np, entries);
42 free(np);
43 }
44
45 return 0;
46 }
補充說明(Supplement):
若只使用 LIST_FOREACH
則功能正常
故第39行以前的程式碼應該是對的
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.114.71.82
推
11/15 18:41, , 1F
11/15 18:41, 1F
→
11/15 18:43, , 2F
11/15 18:43, 2F
推
11/15 18:47, , 3F
11/15 18:47, 3F