C 链表与指针问题

C 链表与指针问题,c,linked-list,void-pointers,C,Linked List,Void Pointers,嘿, 我是C语言的初学者,尝试实现自己的链表实现,基本上如下所示: struct Element { void *value; struct Element *next; }; typedef struct { struct Element *first; struct Element *last; unsigned int size; } LinkedList; void LinkedList_init(LinkedList *this) {

嘿,
我是C语言的初学者,尝试实现自己的链表实现,基本上如下所示:

struct Element
{
    void *value;
    struct Element *next;
};

typedef struct
{
    struct Element *first;
    struct Element *last;
    unsigned int size;
} LinkedList;

void LinkedList_init(LinkedList *this)
{
    this->size = 0;
    this->first = NULL;
    this->last = NULL;
}

void LinkedList_add(LinkedList *this, void *value)
{
    struct Element *node = malloc(sizeof(struct Element));
    node->value = value;
    node->next = NULL;

    if (this->size == 0)
        this->first = this->last = node;
    else
    {
        this->last->next = node;
        this->last = node;
    }

    this->size++;
}
简而言之,我想要一个可以容纳任意类型的链表——我听说,在C语言中,通过使用空指针,这是可能的。 现在,当我想使用该实现(例如,将结构作为值)时,问题就出现了:

typedef struct
{
    int baz;
} Foo;

int main(void)
{
    LinkedList list;
    Foo bar;
    bar.baz = 10;

    LinkedList_init(&list);
    LinkedList_add(&list, (void *) &bar);

    /* try to get the element, that was just added ... */
    Foo *firstElement = (Foo *)list.first;
    /* ... and print its baz value */
    printf("%d\n", firstElement->baz);

    return 0;
}
最后一个printf调用只打印像-1077927056这样的值,看起来像内存地址。所以这可能是指针的问题。在过去几天的网络搜索中,我发现了一个类似的问题(我运气不好),于是我尝试放弃自己的逻辑,并测试了各种随机组合。事实证明,这也是一条死胡同(


对于更有经验的C程序员来说,这可能很简单,但我就是找不到答案。请帮助:D

列表。fist
是一个
结构元素

尝试:


啊,多么简单:D但是非常感谢你的时间。这件事真的一直困扰着我……而且不再需要对
(Foo*)
的演员阵容,这应该是一个线索,表明这是正确的。
Foo *firstElement = (Foo *)(list.first->value);