2010-11-26 98 views
0

嘿,
我在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

回答

7

list.fiststruct Element

尝试:

Foo *firstElement = (Foo *)(list.first->value); 
+0

呃,很简单:D 但是非常感谢你的时间。 这个东西真的不停地给我打扰。 – Paran 2010-11-26 23:38:27