有没有办法比较两个void指针在C中断言相同的类型?

时间:2022-12-27 19:56:43

I am learning C and attempting a crude implementation of a linked list in C. Long story short I have a struct containing only a void pointer(element) and another pointer to the next node.(code to follow) My question is, when passing the head node and some other node into a new function, is there any way to ensure the two elements are of the same type? The two nodes should be able to hold any kind of data. Ive tried comparing with sizeof(), but am unable to deference a void pointer. Thanks in advance!

我正在学习C并尝试在C中粗略实现链表。长话短说我有一个只包含一个void指针(元素)的结构和另一个指向下一个节点的指针。(代码要遵循)我的问题是,当通过时头节点和其他一些节点成新函数,有没有办法确保两个元素属于同一类型?两个节点应该能够保存任何类型的数据。我曾尝试与sizeof()进行比较,但无法推断空指针。提前致谢!

struct Node{
    void* element;
    struct Node* next;
}

This is the code for the nodes, I just need a way to compare them with assert to ensure a linked list with all of the same element types! Thanks!

这是节点的代码,我只需要一种方法将它们与assert进行比较,以确保链接列表具有所有相同的元素类型!谢谢!

2 个解决方案

#1


9  

No -- you generally want to avoid a design like this, but if you really can't avoid it, you typically need to put a enum in the node to tell you the type of data it contains.

不 - 你通常想要避免像这样的设计,但是如果你真的无法避免它,你通常需要在节点中放置一个枚举来告诉你它包含的数据类型。

#2


1  

A void* is precisely a type-less pointer. In other words, all that your program knows is that it's a pointer to SOMETHING. This is useful, but it specifically (intentionally) isn't what you're looking for.

void *正是一个无类型指针。换句话说,你的程序知道的是它是指向SOMETHING的指针。这很有用,但具体(故意)并不是你想要的。

#1


9  

No -- you generally want to avoid a design like this, but if you really can't avoid it, you typically need to put a enum in the node to tell you the type of data it contains.

不 - 你通常想要避免像这样的设计,但是如果你真的无法避免它,你通常需要在节点中放置一个枚举来告诉你它包含的数据类型。

#2


1  

A void* is precisely a type-less pointer. In other words, all that your program knows is that it's a pointer to SOMETHING. This is useful, but it specifically (intentionally) isn't what you're looking for.

void *正是一个无类型指针。换句话说,你的程序知道的是它是指向SOMETHING的指针。这很有用,但具体(故意)并不是你想要的。