2010-11-26 117 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