[英]C - Linked List and pointer problem
Hey, 嘿,
I'm a beginner in C and tried to implement my own linked list implementation, that basically looks like 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++;
}
So in short, I want a linked list that can hold arbitrary types - I heard, this is possible in C by using void pointers. 简而言之,我想要一个可以容纳任意类型的链表-听说,这在C中可以通过使用void指针来实现。 The problem now arises, when I want to use that implementation, for example with a structure as value:
现在,当我想使用该实现时(例如,将结构作为值),就会出现问题:
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;
}
The last printf call just prints values like -1077927056, which look like a memory address. 最后一个printf调用仅打印类似于内存地址的值-1077927056。 So it's probably a problem with pointers.
因此,指针可能是一个问题。 After searching the web the last few days for a similar issue on the web (I had no luck with that), I tried to throw my own logic away and tested various random *& combinations.
在最近几天在网络上搜索了类似的问题(对此我感到不走运)之后,我试图放弃自己的逻辑,并测试了各种随机*&组合。 Turns out, that was a dead end, too.
原来,那也是死胡同。 :(
:(
It's probably something simple for a more experienced C programmer, but I just can't find the answer. 对于一个经验丰富的C程序员来说,这可能很简单,但是我找不到答案。 Please help :D
请帮忙:D
list.fist
is a struct Element
. list.fist
是一个struct Element
。
Try: 尝试:
Foo *firstElement = (Foo *)(list.first->value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.