簡體   English   中英

C中使用宏定義數據結構

[英]Using macros in C to define data structures

我正在嘗試圍繞使用宏來定義數據結構操作的概念進行思考。 下面的代碼是一個使用 FreeBSD 內置列表庫的簡單示例。 在庫中,所有操作都定義為宏。 我也在其他幾個圖書館中看到過這種方法。

我可以看到這有一些優點,例如。 能夠使用任何數據結構作為列表中的元素。 但我不太明白這是如何工作的。 例如:

  1. 什么是stailhead 這似乎是“剛剛”定義的。
  2. 如何將headentries傳遞給 function?
  3. head是什么類型,如何聲明指向它的指針?

這種技術是否有一個標准名稱,我可以用它來搜索谷歌,或者任何解釋這個概念的書? 任何有關此技術如何工作的鏈接或很好的解釋將不勝感激。

感謝Niklas B。我運行了gcc -E並得到了head的定義

struct stailhead {
  struct stailq_entry *stqh_first;
  struct stailq_entry **stqh_last; 
} head = { ((void *)0), &(head).stqh_first };

這是stailq_entry

struct stailq_entry {
 int value;
 struct { struct stailq_entry *stqe_next; } entries;
};

所以我猜headstruct stailhead類型。

#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>

struct stailq_entry {
        int value;
        STAILQ_ENTRY(stailq_entry) entries;
};

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++){
                n1 = malloc(sizeof(struct stailq_entry));   /* Insert at the head. */
                n1->value = i;
                STAILQ_INSERT_HEAD(&head, n1, entries);
        }
        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);
}

首先閱讀本文以了解這些宏的作用。 然后 go 到queue.h 你會在那里得到你的寶庫!

我給你找了幾個金幣——

#define STAILQ_HEAD(name, type)                                         \
struct name {                                                           \
        struct type *stqh_first;/* first element */                     \
        struct type **stqh_last;/* addr of last next element */         \
}

讓我們深入挖掘並回答您的問題

什么是尾巴? 這似乎是“剛剛”定義的。

#define STAILQ_HEAD(name, type)                                         \
struct name {                                                           \
        struct type *stqh_first;/* first element */                     \
        struct type **stqh_last;/* addr of last next element */         \
}
 STAILQ_HEAD(stailhead, entry) head =
 STAILQ_HEAD_INITIALIZER(head);
 struct stailhead *headp;            /* Singly-linked tail queue head. */

所以stailhead是一個結構

如何將頭部和條目傳遞給 function?

#define STAILQ_ENTRY(type)                                              \
struct {                                                                \
        struct type *stqe_next; /* next element */                      \
}

所以entrieshead (如前所述)只是結構,您可以像傳遞其他結構一樣傳遞它們。 &structure_variable

head 是什么類型,如何聲明指向它的指針?

已經說明了!

閱讀此手冊頁以獲取漂亮的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM