CS157 Struct2
We can define the values of user defined types at the declaration. The syntax is similar to that of array initialization.
typedef struct { char name[50]; int age; char phone[15]; float height; } person; int main() { person company[] = {{"Robert", 45, "970-555-2222", 5.9}, {"Sally", 38, "303-555-1111", 5.5}}; return 0; }
.
operator.
var.stype.age
.
typedef struct { int age; union { int num_new_teeth; // if age <= 2 int school_grade; // if age <= 25 int fake_hips; // if age >= 60 } info; } person; int main() { person bob; bob.age = 75; bob.info.fake_hips = 2; return 0; }
A union
doesn’t have to have a type name:
typedef struct { int age; union { int num_new_teeth; // if age <= 2 int school_grade; // if age <= 25 int fake_hips; // if age >= 60 }; // no name } person; int main() { person bob; bob.age = 75; bob.fake_hips = 2; return 0; }
int main() { item vend[20]; vend[0].type = beverage; strcpy(vend[0].name, "Coke"); vend[0].fl_ounces = 12; vend[0].cost = 1.25; vend[0].count = 10; vend[1].type = candy; strcpy(vend[1].name, "KitKat"); vend[1].pieces = 4; vend[1].cost = 0.95; vend[1].count = 7; vend[2].type = snack; strcpy(vend[2].name, "Pringles"); vend[2].servings = 2; vend[2].cost = 1.10; vend[2].count = 5; return 0; }
typedef struct { enum { beverage, candy, snack } type; char name[30]; union { float fl_ounces; int pieces; int servings; }; float cost; int count; } item;
typedef struct { unsigned char age; char gender; } person; int main() { person bob; person *p = &bob; (*p).age = 7; p->age = 6; return 0; }
->
operator.