嘿,
我是 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 中可以通过使用 void 指针来实现。现在问题出现了,当我想使用该实现时,例如将结构作为值:
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