Download presentation
Presentation is loading. Please wait.
Published byValentine Johnson Modified over 9 years ago
1
1 C Language Structures
2
2 Topics Concept of a structure Concept of a structure Structures in c Structures in c Structure declaration Structure declaration Structure variable definition Structure variable definition Structure usage Structure usage Member access Member access Allowed operations Allowed operations Functions Functions
3
3 Concept of a Structure A programmer-defined data type Logical grouping of data Can consist of different types of data Useful for organizing data Sometimes called a record elsewhere
4
4 Concept of a Structure john.smith john.smith 35 35 3.14 3.14 70.5f 70.5f m service service Employee Employee: name age pension salary sex years service character array integer floating point (double) floating point character int
5
5 Structures in C Use the struct keyword A structure declaration creates a new type A structure variable definition creates the actual space for a structure Data items of a structure are called its members
6
6 Structure Declaration struct employee { char name [ 30 ]; int age; double pension; float salary; char sex; int service; }; a new type! tag members semicolon
7
7 Structure Variable Definition struct employee staff; struct employee partTime; variables of the new type! tagstructure variable names
8
8 Structure Variable Definition with Initializer struct employee newbie = { “john.smith”, 35, 3.14, 70.5f, ‘m’, 0 }; variable with initializer list
9
9 Structure Declaration and Variable Definition struct employee { char name [ 30 ]; int age; double pension; float salary; char sex; int service; } salesDept[100 ]; a new type and a variable definition Note: this is an array variable declaration tag structure variable name
10
10 Tag-less Structure Declaration and Variable Definition struct { char name [ 30 ]; int age; double pension; float salary; char sex; int service; } newEmployee; a new tag-less type and a variable definition No tag structure variable name Note: can’t define another structure variable later with an unnamed type
11
11 Structure Usage Member access Allowed operations Functions
12
12 Member Access General format: structVariable.memberName Examples: newEmployee.salary salesDept[22].age salesDept[i].service salesDept[employeeNumber].salary
13
13 Structure Member Access struct employee { char name [ 30 ]; int age; double pension; float salary; char sex int service; } finDept[100 ]; void print_ages (void) { int i; for ( i = 0; i < 100; i++) { printf (“Age is %d\n”, finDept[i].age); }
14
14 Allowed Operations Can copy or assign as a unit (but not allowed to compare 2 structures) Access its members Use sizeof() operator to obtain size in bytes sizeof (struct employee)
15
15 Functions Can pass to/from a function: a member of a structure an entire structure Passes a whole structure
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.