Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structs CSE 2451 Rong Shi. Structures Structure – one or more values, called members, with possibly dissimilar types that are stored together – Group.

Similar presentations


Presentation on theme: "Structs CSE 2451 Rong Shi. Structures Structure – one or more values, called members, with possibly dissimilar types that are stored together – Group."— 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 { } ;

4 Example struct fraction { int numerator; int denominator; }; 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 struct PIXEL { 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 int a[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: struct DATAMEMBERS * s = &single; s->f Note: (*s).f == s->f

8 typedefs and structs typedef ; typedef struct { 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; };


Download ppt "Structs CSE 2451 Rong Shi. Structures Structure – one or more values, called members, with possibly dissimilar types that are stored together – Group."

Similar presentations


Ads by Google