这种结构用作链表的头部:
struct lista
{
struct lista* next;
struct lista* prev;
};
当 next 和 prev 都指向 struct 本身时,则链表为空。 以下宏可用于初始化结构:
#define LISTA_INIT_EMPTY(list) { .next = (list), .prev = (list) }
这样:
struct lista my_list = LISTA_INIT_EMPTY(&my_list);
但是,有没有办法通过以下方式做同样的事情,没有宏参数?:
struct lista my_list = LISTA_INIT_EMPTY;
我尝试了以下方法,但它导致了编译错误:
#define LISTA_INIT_EMPTY { .next = &.next, .prev = &.next }
最佳答案
嗯,我看到的唯一方式是不愉快的:
#define LISTA_INIT_EMPTY { .next = (&my_list), .prev = (&my_list) }
一点都不好,因为它只有在您的变量名为 my_list
时才有效。并且没有很好的方法,因为 this
在 C 中不存在。
为什么不使用 NULL
而不是指向“this”?如果这不能令人满意,保留参数化宏可能是最好的。
编辑:(感谢下面 R 的评论,我终于明白了需要):
由于没有“this”而且只输入一次变量名,我建议使用这样的宏:
#define CREATE_EMPTY_LISTA(name) struct lista name = { .next=&name, .prev=&name }
在后面的代码中:
CREATE_EMPTY_LISTA(my_list); // creates and initializez my_list at the same time
关于c - 使用指定初始化程序时是否有可能获得指向 'this' 结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7161937/