I’m following a pseudocode snippet in a CompSci paper and trying to implement it in C. In this paper, I have two structs, say A and B. One of them goes something like this:
struct A {
B* next;
int data;
}
while B looks like
struct B {
A* next;
}
Now, for a given instantiation a of A and b of B, at some point the algorithm tells me to do two things:
- if
ais notB, then do stuff, - a = b
Now, I cannot do reflection in C, and I will obviously get incompatible pointer types for the second requirement. I thought about having a union in the A struct, and perhaps that would help, but I’d like to ask you guys if there’s a good design I’m missing.
You are venturing into dangerous territory here. It appears that you are trying to implement polymorphism in a language which has no built in support for it.
There are several schemes you could use which allow you to have an
struct A*actually point to memory containing astruct B. A union is probably the least dangerous. But as you point out, there is no reflection. Any pointer only knows that it points to a block of memory, and one way to interpret that block if it is dereferenced.voidpointers don’t even know that last part. The only way to do type identification is to insert a value identifying the type somewhere in the structure.Something like this:
-edit-
on the other hand, if the content of the structures is as simple as you describe, you could
simply add an
isBmember tostruct a, and only use one type.