Structure and Union Types CCU COMM Structure Type

  • Slides: 13
Download presentation
Structure and Union Types 程式設計 潘仁義 CCU COMM

Structure and Union Types 程式設計 潘仁義 CCU COMM

Structure Type Definition structured data objects, can be defined by users #define STRSIZ 10

Structure Type Definition structured data objects, can be defined by users #define STRSIZ 10 typedef struct { char name[STRSIZ]; double diameter; int moons; double orbit_time, rotation_time; } planet_t; /* diameter in km */ /* number of moons */ /* years to orbit sun once */ /* hours to rotate once */ int main () { planet_t current_planet, blank_planet = {“”, 0, 0}; int status = scan_planet(&current_planet); /* 等會看 */ current_planet = get_planet(); print_planet(current_planet); …

Assigning Values to Components of Variable current_planet

Assigning Values to Components of Variable current_planet

Function with a Structured Input Parameter

Function with a Structured Input Parameter

Function Comparing Two Structured Values for Equality

Function Comparing Two Structured Values for Equality

Function with a Structured Output Argument 也可寫成 & plnp->diameter, &plnp->moons, & plnp->orbit_time, &plnp->rotation_time);

Function with a Structured Output Argument 也可寫成 & plnp->diameter, &plnp->moons, & plnp->orbit_time, &plnp->rotation_time);

Data Areas of main and scan_planet during Execution of status = scan_planet (&current_planet);

Data Areas of main and scan_planet during Execution of status = scan_planet (&current_planet);

Function get_planet Returning a Structured Result Type

Function get_planet Returning a Structured Result Type

Data Type planet_t and Basic Operations 例如: 課本的 complex Figure 11. 10

Data Type planet_t and Basic Operations 例如: 課本的 complex Figure 11. 10

Parallel Arrays and an Array of Structures int id[50]; double gpa[50]; struct { int

Parallel Arrays and an Array of Structures int id[50]; double gpa[50]; struct { int id; double gpa; } stulist[50];

Union types Union To deal with situations in which one needs a data object

Union types Union To deal with situations in which one needs a data object that can be interpreted in a variety of ways. typedef union { int wears_wig; /*載假髮嗎? */ char color[20]; } hair_t; typedef struct { int bald; /*禿頭嗎? */ hair_t h; } hair_info_t;

Function That Displays a Structure with a Union Type Component

Function That Displays a Structure with a Union Type Component

Q&A union 可以用 -> 嗎? struct planet_t a, b; a = b; /* 可這麼寫嗎?

Q&A union 可以用 -> 嗎? struct planet_t a, b; a = b; /* 可這麼寫嗎? */ if(a == b) {} /* 可這麼寫嗎? */ (*plnp). name *plnp. name plnp->name &plnp->name 小心:union 的內容該如何解釋?