1 / 9

Structs

Structs. CSE 2451 Rong Shi. 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

Télécharger la présentation

Structs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Structs CSE 2451 Rong Shi

  2. 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

  3. Struct definition • struct <tag> {<member_list>} <variable_list>;

  4. 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

  5. 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;

  6. 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];

  7. 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

  8. 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)

  9. Struct members of the same type struct SELF_REF1 { int a; struct SELF_REF1 b; }; Struct SELF_REF2 { int a; struct SELF_REF2 *b; };

More Related