There are several options available. Among them:
Switch to C++. You can then derive your three structs from a common base struct that includes the data
member. Or use classes instead of structs and do the same thing. (This isn't as unhelpful as it might sound -- most C compilers these days also compile C++, and switching may be as simple as changing a file extension or compiler flag.)
Use a single struct containing a union for the second members. That way, you have only one type to deal with.
Use a single struct without the union and name the second member animals
.
Create a struct Data
that holds the data
member, and then "piggyback" any other members onto that. That is, make sure that an instance of the Data
struct is the very first member of One
, Two
, and Three
. Then use type struct Data *
when you only want to refer to the common part.
Look into ways to simulate OO-style polymorphism in C. Warning: it's not pretty.
Pass a pointer to the data
member in each struct rather than a pointer to the entire struct.
Here's an example of that last strategy:
void swapData(int* data1, int* data2)
{
int temp = *data1;
*data1 = *data2;
*data2 = temp;
}
// call it like this:
swapData(&(dog->data), &(cat->data));
Any way you slice it, the swapData()
function needs to know what it's dealing with. Plain old C doesn't provide inheritance polymorphism, so there's not a straightforward way to create a single base type that encompasses all three of your structs. So, you have to resort to passing just part of a struct, or casting the struct to a simpler type, etc. Since the data
member is actually the first item in each of the structs, you can use the swapData()
I provided above but simplify the call a little bit:
swapData((int*)dog, (int*)cat);
That's sneaky, though, and harder to understand (or maybe easier to misunderstand) even though it's shorter.