简体   繁体   English

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

[英]Is there ANY way to compare two void pointers to assert the same type in C?

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? 我正在学习C并在C​​中尝试粗略实现链表。长话短说我有一个只包含一个void指针(元素)的结构和另一个指向下一个节点的指针。(代码要遵循)我的问题是,当通过时头节点和其他一些节点成新函数,有没有办法确保两个元素属于同一类型? 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. 我已经尝试与sizeof()进行比较,但我无法顺从void指针。 Thanks in advance! 提前致谢!

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

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

A void* is precisely a type-less pointer. void *正是一个无类型指针。 In other words, all that your program knows is that it's a pointer to SOMETHING. 换句话说,你的程序知道的是它是指向SOMETHING的指针。 This is useful, but it specifically (intentionally) isn't what you're looking for. 这很有用,但它具体(有意)不是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM