I am learning C and apologies if this the question isn't even asked right
But my question is, if I have a typedef struct that contains a union of two other typedef structs, do I need to instantiate all the variables?
For example, if I have the following code:
typedef struct dog {
char *breed;
long weight;
} dog;
typedef struct cat {
bool isBlackCat;
int numberOfLives;
} cat;
typedef struct animal {
int id;
int ownerID;
char *name;
bool isDog;
union {
struct dog aDog;
struct cat aCat;
} animals;
} animal;
If I were to use the above structure in a function like so:
Adoption adoptAnimal(char *nameParam, bool type, int ownerId) {
Adoption pet = (Adoption) malloc(sizeof(struct animal));
pet -> name = (char*) malloc((1 + strlen(nameParam)) * sizeof(char));
strcpy(pet->name, nameParam);
pet -> id = getId(); //function that generates an id
pet -> ownerId = ownerId;
pet -> isDog = type;
// if type = 1, it's a dog
if (type) {
pet -> animals.aDog.breed = some breed;
pet -> animals.aDog.weight = some weight;
} else {
pet -> animals.aCat.lives = 9;
pet -> animals.aCat.isBlackCat = 1;
}
return pet;
}
Is this proper/legal use of a typedef struct that contains a union? The way the function is set up, the variables from the dog or cat struct will be assigned, but not both, is that allowed? Or do I need to assign all of the variables from both structs
Thank you