Unit 8: Structures - Tin học đại cương (IT1110) | Trường Đại học Bách khoa Hà Nội
Unit 8: Structures
Preview text:
lOMoAR cPSD| 27879799
Downloaded by VietJack TV Official (vietjackvideos@gmail.com) lOMoAR cPSD| 27879799 Data Structures (struct)
• Arrays require that all elements be of the same data type.
• It is necessary to group information of different data
types: list of products (productid, name, dimensions, weight, cost)
• Structures can store combinations of character,
integer floating point and enumerated type data.
Name of the data type : struct. lOMoAR cPSD| 27879799 Structures (struct)
• A struct is a structured data type composed of
members that are each standard or structured data types.
• A single struct would store the data for one object.
An array of structs would store the data for several objects.
• A struct can be defined in several ways as illustrated in the following examples: 3 lOMoAR cPSD| 27879799 Declaring Structures (struct) Reserves Space struct my_examp le { i n lOMoAR cPSD| 27879799 */ t l a b e l ; char lette r; char 5 lOMoAR cPSD| 27879799 nam e[20 ]; } mystruct ; lOMoAR cPSD| 27879799 Length Length Length a, b, len ; Length numbers[10] ; 7 lOMoAR cPSD| 27879799 lOMoAR cPSD| 27879799
Accessing Struct Members (Fields)
Individual members of a struct variable may be
accessed using the structure member operator (the dot, “.”): mystruct.letter ;
Or , if a pointer to the struct has been declared and initialized
Some_name *myptr = &mystruct ;
by using the structure pointer operator (the “->“): myptr -> letter ;
which could also be written as: (*myptr).letter ; 9 lOMoAR cPSD| 27879799 Sample Program With Structs lOMoAR cPSD| 27879799 Sample Program With Structs printf ( printf ( 11 lOMoAR cPSD| 27879799 EXERCISE
• Suppose we have the user-defined structure baby, including: • Name is a string
• BirthYear is an integer between 2015 and 2019
• BirthMonth is an integer between 1 and 12
• Weight is a real number between 0 and 10
• Sex is an integer that receives only 2 values :1 for boys and 0 for girls
• Read information about n babies (1<=n<=10) into array B lOMoAR cPSD| 27879799
• Read information about babies until we get weight 0 . 13 lOMoAR cPSD| 27879799 Name Weight Sex right justified.