CS157

CS157: Intro to C, Part II

Spring 2018

Struct 2

See this page as a slide show

Structures, part 2

CS157 Struct2

Initialization of User Defined Types

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;
}

Nested Types

Nested User Defined Types

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;
}

Anonymous unions

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;
}

Complex example

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;

Pointers and Structs

typedef struct {
    unsigned char age;
    char gender;
} person;

int main() {
    person bob;
    person *p = &bob;
    (*p).age = 7;
    p->age = 6;
    return 0;
}

Modified: 2017-12-19T11:20

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building