Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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!

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!

like image 534
occulum Avatar asked Mar 20 '12 04:03

occulum


2 Answers

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.

like image 64
Jerry Coffin Avatar answered Nov 10 '22 01:11

Jerry Coffin


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.

like image 26
mfsiega Avatar answered Nov 10 '22 00:11

mfsiega