嘿,
我是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++;
}
简而言之,我想要一个可以保存任意类型的链表 - 我听说,这可以通过使用void指针在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
答案 0 :(得分:7)
list.fist
是struct Element
。
尝试:
Foo *firstElement = (Foo *)(list.first->value);