【问题标题】:C - Linked List and pointer problemC - 链表和指针问题
【发布时间】:2011-05-16 09:47:11
【问题描述】:

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

【问题讨论】:

    标签: c linked-list void-pointers


    【解决方案1】:

    list.fiststruct Element

    试试:

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

    【讨论】:

    • 啊,多么简单 :D 但是非常感谢您抽出宝贵的时间。这件事真的一直困扰着我。
    • ...不再需要强制转换为(Foo *),这应该表明这是在正确的轨道上。
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多