Do you know what union means in C? Your union doesn't have 3 members. Your union has 4 members. Among those 4 members, how many do you want to store values in?
Why didn't you ask your TA?
Do you know what union means in C? Your union doesn't have 3 members. Your union has 4 members. Among those 4 members, how many do you want to store values in?
Why didn't you ask your TA?
You may be misunderstanding the purpose of a union.
A union is typically used to store one item that may be in one of several forms. For example:
// Define an array of 20 employees, each identified either by name or ID.
union ID {
char name[10]; // ID may be a name up to 10 chars...
int serialNum; // ... or it may be a serial number.
} employees[20];
// Store some data.
employees[0].serialNum = 123;
strcpy(employees[1].name, "Manoj");
The critical difference between a struct
and a union
is that a struct
is an aggregate of many pieces of data, but a union
is an overlayment: you may store only one of the elements because they all share the same memory. In the example above, each element in the employees[]
array consists of 10 bytes, which is the smallest amount of memory that can hold either 10 char
s or 1 int
. If you reference the name
element, you can store 10 char
s. If you reference the serialNum
element, you can store 1 int
(say 4 bytes) and cannot access the remaining 6 bytes.
So I think you want to use different, separate structures to represent the family members. What you've done appears to be cramming several square pegs into one round homework assignment. :-)
Note for advanced readers: please don't mention padding and word alignment. They're probably covered next semester. :-)
You need to read this question about unions. You want something more like:
struct family {
struct name {
int gender;
int married;
blah
} names;
union {
struct male { blah } male_ancestor;
struct female_unmarried { blah } female_unmarried_ancestor;
struct female_married { blah } female_married_ancestor;
};
}
then you can test family.names.gender and family.names.married to determine which member of the union to use.