90 likes | 245 Views
Structs. CSE 2451 Matt Boggus. Structures. Structure one or more values, called members, with possibly dissimilar types that are stored together Group together different types of variables under the same name Compared to arrays Data members may have different size
E N D
Structs CSE 2451 Matt Boggus
Structures • Structure • one or more values, called members, with possibly dissimilar types that are stored together • Group together different types of variables under the same name • Compared to arrays • Data members may have different size • Not as easy to access members ( i.e. no [], use dot operator . instead ) • Structure variable names are not constant pointers like array names
Struct definition • struct <tag> {<member_list>} <variable_list>;
Example struct fraction { intnumerator; intdenominator; }; struct fraction f1, f2 = {.numerator = 1, .denominator = 1}; f1.numerator = 2; f1.denominator = 3; f2 = f1; if(f1 == f2) // invalid, == not defined for structs
Struct names/tags • The tag field sets a name to the struct • Allows creation of structures of the same type structPIXEL { float red; float green; float blue; } ; struct PIXEL p; struct PIXEL image[20], *imp;
Example of struct data members struct DATAMEMBERS { float f; // single variable inta[20]; // array long *lp; // pointer struct PIXEL pix; // a different struct struct PIXEL image[10]; // array of different structs struct PIXEL *imp; // pointer to a different struct } single, array [10];
Struct data member access • Dot operator ( . ) – for variables • struct_variable_name.member_name • Ex: single.f array[2].image[10].red • Indirection ( -> ) – for pointers • Pointer_to_struct->member_name • Ex: structDATAMEMBERS * s = &single; s->f Note: (*s).f == s->f
typedefs and structs • typedef<type> <name>; typedefstruct { float red; float green; float blue; } Pixel; Pixel p; Pixel image[100], *imp; • (Avoids the need to type struct in front of struct name)
Struct members of the same type struct SELF_REF1 { int a; struct SELF_REF1 b; }; Struct SELF_REF2 { int a; struct SELF_REF2 *b; };