Download presentation
Presentation is loading. Please wait.
1
Lecture 13 Structs
2
Introduction Our variables until now
Single variable int i, char c, float f Set of same type elements: Array int a[10], char c[20] If data are not same type, but related? Example: Information about students Student Name Student Family Name Student Number Student Grade
3
Introduction How to save the student information?
1- Use separated variables st_name[20]; st_fam_name[20]; char id; grade; int 2- Put them altogether, they are related Use struct
4
Structure Basics A structure is a collection of data values, called data members, that form a single unit. Unlike arrays, the data members can be of different types.
5
struct: version 1 Set of related variables struct in C (version 1)
Each variable in struct has its own type struct in C (version 1) struct { <variable declaration> } <identifier list>;
6
struct (version 1): Example
char char st_name[20]; st_fam_name[20]; int id; int grade; } st1; We declare a variable st1 Type of st1 is struct id is a member of the struct grade is a member of the struct
7
struct (version 1): Example
char char st_name[20]; st_fam_name[20]; int id; int grade; } st1, st2, st3; We declare three variables: st1, st2, st3 Type of st1, st2, st3 is the struct In this model, we cannot reuse the struct definition in other location (e.g., input of function)
8
struct: Version 2 struct in C (version 2) struct <tag> {
<variable declaration> }; struct <tag> <identifiers>;
9
struct (version 2): Example
student { st_name[20]; st_fam_name[20]; struct char int id; int grade; }; struct student st1, st2, st3; We define a struct with tag student We don’t allocate memory, it is just definition We declare variables st1, st2, st3 from student
10
Declaring Structures (struct)
The name "employee" is called a structure tag Variables declared within the braces of the structure definition are the structure’s members struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; }; struct employee Ali, emp[10]; struct employee { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; } Ali, Sara, empDTS[20]; struct employee Reza, *emp; struct { char firstName[ 20 ]; char lastName[ 20 ]; int age; char gender; double hourlySalary; } Ali;
11
Declaring Structures (struct)
Members of the same structure type must have unique names, but two different structure types may contain members of the same name without conflict Each structure definition must end with a semicolon struct employee { char Name[ 20 ]; char Name[ 20 ]; // Error!!! int age; char gender; double hourlySalary; } Ali, Sara, empDTS[20]; struct employee Reza, *emp; struct Student { char Name[ 20 ]; // OK int age; char gender; }; struct Student Ce40153[80];
12
Structures as New Data Type
When we define a new struct, in fact we are define a new data type Then we use the new data type and define variables So, we need to learn how to work it Access to members Operators for struct Pointer to struct struct in functions Array of struct
13
Size of struct char st_fam_name[20]; int id; int grade;
struct std_info{ char st_name[20]; char st_fam_name[20]; int id; int grade; }; struct std_info st1, st2, sizeof(struct std_info) ? st3; sizeof(st1) ?
14
Using struct We should declare variables from struct type
Versions 1, 2, 3.1, 3.2 How to access to the members of struct <struct variable>.<element name> st1.st_name is a array of char in struct st1 st2.grade is a int variable in struct st2
15
Example
16
struct initialization
17
struct initialization
Similar to array initialization information st1 = {"Ali", "Karimi", “Ali” is assigned to st_name “Karimi” is assigned to st_fam_name 9222 is assigned to id 10 is assigned to grade 9222, 10}; Order of values should be exactly the order of the members The number of values must be <= the number of members Initial values cannot be assigned in struct definition
18
Initializing Structures
x y r color 5.0 width 10.0 height
19
Nested struct struct date_type{ int d, m, y; };
student{ name[20]; fam_name[20]; struct char char int int id; grade; struct date_type }; date;
20
Nested struct struct student st1 = {"A","B",1,10,{2,3,1368}};
st2.name = "C"; st2.fam_name = "D"; st2.id = 2; = st2.grade 15; st2.date.rooz st2.date.mah st2.date.sal = 10; = 5; = 1390;
21
Declaring Structures (struct)
A structure cannot contain an instance of itself For example, a variable of type struct employee cannot be declared in the definition for struct employee A pointer to struct employee, however, may be included A structure containing a member that is a pointer to the same structure type is referred to as a self-referential structure struct employee2 { // … double hourlySalary; struct employee2 person; /* ERROR */ struct employee2 *ePtr; /* pointer */ };
22
Structure and operators
23
struct: Copy and Assignment
date_type{ rooz, mah, struct int }; sal; date_type d1, d2 = {2, 1, 1360}; /* Copy all data from d2 to d1. */ d1 = d2; /* d1.rooz = d2.rooz; d1.mah d1.sal = d2.mah; = d2.sal; */
24
struct: Copy and Assignment
struct test_type{ char name[10]; int id[10]; }; struct 3}}; test_type d1, d2 = {"ABC", {1, 2, d1 = d2; /* d1.name d1.id = "ABC"; = {1, 2, 3}; */
25
struct: Comparing We cannot compare struct variables
==, <=, <, >, >= cannot be used for struct information st1, st2; if(st1 <= st2){ ... } // Compile Error
26
struct: Comparing We can compare members of structs
27
Array of struct: Definition
struct is a type We can define array of struct
28
.ﺪﻨﻛ ﺪﻴﻟﻮﺗ ﺍﺭ ﺖﺳﺍ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍ ﺮﺘﺸﻴﺑ
34 ﺍﺭ ﻥﺎﻳﻮﺠﺸﻧﺍﺩ ﻩﺮﻤﻧ ﻭ ﻩﺭﺎﻤﺷ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﺎﻬﻧﺁ ﻩﺮﻤﻧ ﻪﻛ ﻲﻧﺎﻳﻮﺠﺸﻧﺍﺩ ﺖﺴﻴﻟ ﻭ ﺩﺮﻴﮕﺑ .ﺪﻨﻛ ﺪﻴﻟﻮﺗ ﺍﺭ ﺖﺳﺍ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍ ﺮﺘﺸﻴﺑ
29
Quick overview We can define new data type using Structure.
Syntax of structure definition is:
30
Example
31
Example
32
Example
33
#include <stdio.h>
36 #include <stdio.h> .ﺩﺮﻴﮕﺑ ﺍﺭ ﻥﺎﻳﻮﺠﺸﻧﺍﺩ ﺯﺍ ﺖﺴﻴﻟ ﻚﻳ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﻮﺠﺸﻧﺍﺩ ﺮﮔﺍ ﻭ ﺩﺮﻴﮕﺑ ﻲﻳﻮﺠﺸﻧﺍﺩ ﻩﺭﺎﻤﺷ ﻚﻳ ﺲﭙﺳ .ﺪﻫﺩ ﻥﺎﺸﻧ ﺍﺭ ﻱﻭ ﺕﺎﻋﻼﻃﺍ ﺖﺳﺍ ﺖﺴﻴﻟ ﺭﺩ int main(void){ struct std{ char name[20]; int id; int grade; }; const int num = 25; struct std std_arr[num]; int sid, i; for(i = 0; i < num; i++){ printf("Enter Name, ID and grade\n"); std_arr[i].name); &(std_arr[i].id)); &(std_arr[i].grade)); scanf("%s", scanf("%d", }
34
printf("Enter Search scanf("%d", &sid);
37 ID: "); for(i = 0; i < num; i++) if(std_arr[i].id == sid){ printf("Found:\n"); printf("Name = %s\n", std_arr[i].name); printf("ID = %d\n", std_arr[i].id); printf("Grade = %s\n", std_arr[i].grade); } return 0;
35
Pointer and Structure
36
Pointer to struct: Definition
A variable of struct type is a variable It has address, we can have pointer to it std{ id; grade; struct int int }; struct struct std st1; std *ps; ps = &st1;
37
Pointer to struct: Usage (Version 1)
We can use *pointer method *ps means the content of the address that ps refers to there it is struct (*ps).id is the member of struct that ps refers to it (*ps).grade is the member of struct that ps refers to it
38
Pointer to struct: Usage (Version 2)
We can use “->" method struct std{ int id; int grade; }; struct std st1, *ps; ps = &st1 int y = ps->id; int z = ps->grade; // (*ps).id // (*ps).grade
39
Example
41
Exapmle ﻞﺻﺎﺣ ﻭ ﺩﺮﻴﮔﻲﻣ ﺍﺭ ﺎﻳﻮﮔ ﺩﺪﻋ ﻭﺩ ﻪﻛ ﻲﻌﺑﺎﺗ
.ﺪﻨﻛﻲﻣ ﺪﻴﻟﻮﺗ ﺍﺭ ﺎﻬﻧﺁ ﻖﻳﺮﻔﺗ ﻭ ﻊﻤﺟ Exapmle
42
Structures and Function
43
struct & Functions struct is a type so It can be used
In input parameter list of functions Call by value Call by reference In return type of functions void f(struct std s1); // call by value input void g(struct std *s2); // call by reference struct std h(void); // return type
44
struct & Functions: Example
struct as call by value input parameter
45
struct & Functions: Example
struct as call by reference input parameter
46
struct & Functions: Example
struct as output of function information create_st_info(void){ information scanf("%s", scanf("%s", scanf("%d", scanf("%d", return tmp; tmp; tmp.name); tmp.fam_name); &tmp.id); &tmp.grade); } //----- Calling the function information st1; st1 = create_st_info(); ----
47
Scope of struct definition
A struct can be used only In the defined scope After definition if sruct is defined in a function It can be used only in the function No other function knows about it If struct is defined as a global It can be used in all function after the definition
48
Scope of struct variables
The scope of struct variables are the same other variables Member variables are local to the structure. If struct variable is global Initialized to zero and visible to the functions after its declaration If struct variable is automatic local There is not any initial value, destroyed when the block finishes If struct variable is static Kept in memory until program finishs
49
ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺎﻫﻥﺎﻣﺯ ﺯﺍ ﻪﻋﻮﻤﺠﻣ ﻚﻳ ﻱﺍﻪﻣﺎﻧﺮﺑ
#include <stdio.h> ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺎﻫﻥﺎﻣﺯ ﺯﺍ ﻪﻋﻮﻤﺠﻣ ﻚﻳ ﻱﺍﻪﻣﺎﻧﺮﺑ ،ﺖﻋﺎﺳ ﻞﻣﺎﺷ ﻥﺎﻣﺯ ﺮﻫ .ﺪﻨﻛ ﺐﺗﺮﻣ ﺍﺭ ﺎﻬﻧﺁ .ﺖﺳﺍ ﻪﻴﻧﺎﺛ ﻭ ﻪﻘﻴﻗﺩ struct time{ int hour; int min; int sec; }; /* 1: t1 > t2, 0: int time_cmp(struct time t1, struct t1 = t2, -1: t1 < t2 */ time t2){ if(t1.hour > t2.hour) return 1; else if(t2.hour > t1.hour) return -1; else if(t1.min return 1; else if(t2.min return -1; else if(t1.sec return 1; else if(t2.sec return -1; else return 0; > t2.min) > t1.min) > t2.sec) > t1.sec) }
50
void time_swap(struct time *t1, struct time tmp; struct time *t2){ tmp
= *t1; *t1 *t2; *t2 tmp; } /* Find index of max element */ int rec_max(struct time time_arr[], int start, int int tmp, res; if(start == end) res = start; else{ tmp = rec_max(time_arr, start + 1, end); if(time_cmp(time_arr[start], time_arr[tmp]) res = start; else res = tmp; } return res; end){ >= 0) }
51
/* Recursively sort array from start to end */
void rec_sort(struct time time_arr[], int start, int int max; if(start == end) return; end){ max = rec_max(time_arr, start, end); time_swap(&(time_arr[start]), &(time_arr[max])); rec_sort(time_arr, start + 1, end); } /* Print Array elements void print_array(struct from start to end */ time time_arr[], int start, int end){ for(int i = start; i <= end; i++) printf("%d:%d:%d, ", time_arr[i].hour, time_arr[i].min, time_arr[i].sec); printf("\n"); }
52
int main(void){ struct time ta[5] = {{4, 0, 1}, {6, 1, 0}, {2, 2, 1}, 4, 7}, {8, 5, 4}}; print_array(ta, rec_sort(ta, 0, print_array(ta, 0, 4); 4); 0, 4); return 0; }
53
Enum Introduction Some data are naturally ordered
Days of week Months of year We want to use the order, e.g. The number of visitors per day The salary per month We need an array visitors[0] The number of visitors in Saturday visitors[1] The number of visitors in Sunday
54
Enum Introduction Enumeration is a mechanism to assign a name for each number E.g. visitors[saturday], visitors[friday] salary[april], salary[may]
55
enum enum is used to define a set of names and their corresponding numbers enum tag {name_1, name_2, …, name_N} tag is the enumeration type We use it to define variables name_1 = 0 name_2 = 1 name_i = (name_(i-1)) + 1
56
enum enum week {sat, sun, mon, tue, wed, thu, fri};
sat = 0, sun = 1, mon = 2, …, fri = 6 enum year {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, des}; jan = 0, feb = 1, …, nov = 10, des = 11
57
enum We can assign the numbers
enum week {sat = 1, sun, wed, thu, fri}; mon, tue, sat = 1, sun = 2, mon = 3, …, fri = 7 enum condition {False = 0, True, No = 0, Yes, Ghalat = 0, Dorost}; False = No = Ghalat = 0 True = Yes = Dorost = 1
58
enum After definition of an enumeration
We can use the tag to declare variables We can use the names to assign values to the variables enum week {sat, sun, mon, tue, wed, thu, fri}; enum week day = sat; for(day = sat; day <= fri; day++)
59
Example: Read the number of visitors
enum week {sat, sun, mon, tue, wed, thu, fri}; int visitors[7]; enum week day; sat; day <= fri; for(day = day++) scanf("%d", &visitors[day]);
60
Enumeration Values in an enum start with 0, unless specified otherwise, and are incremented by 1 The identifiers in an enumeration must be unique The value of each enumeration constant of an enumeration can be set explicitly in the definition by assigning a value to the identifier Multiple members of an enumeration can have the same constant value
61
Unions A union is a derived data type—like a structure—with members that share the same storage space a union shares the space instead of wasting storage on variables that are not being used The members of a union can be of any data type The number of bytes used to store a union must be at least enough to hold the largest member Only one member, and thus one data type, can be referenced at a time
62
Unions representation
c union myDataUnion { int i; char c; float f; } u1, u2; union myDataUnion u3; u1.i = 4; u1.c = ’a’; i f
63
Unions The operations that can be performed on a union are the following: assigning a union to another union of the same type taking the address (&) of a union variable accessing union members using the structure member operator and the structure pointer operator Unions may not be compared using operators == and != same as the structures
64
Unions In a declaration, a union may be initialized with a value of the same type as the first union member union a { int a; // OK char b[4]; }; union a x = {10}; printf("%d", x.a);
65
Unions ? A union value doesn’t "know" which case it contains
How should your program keep track whether elt1, elt2 hold an int or a char? ? union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF; if (elt1 currently has a char) … Basic answer: Another variable holds that info
66
Tagged Unions Tag every value with its case
enum Union_Tag {IS_INT, IS_CHAR}; struct TaggedUnion { enum Union_Tag tag; union { int i; char c; } data; }; Enum must be external to struct, so constants are globally visible Struct field must be named
67
Bit-field Structures C enables you to specify the number of bits in which an unsigned or int member of a structure or union is stored This is referred to as a bit field Bit fields enable better memory utilization by storing data in the minimum number of bits required Bit field members must be declared as int or unsigned A bit field is declared by following an unsigned or int member name with a colon (:) and an integer constant representing the width of the field (i.e., the number of bits in which the member is stored)
68
Bit-field Structures Notice that bit field members of structures are accessed exactly as any other structure member struct Flags { int f1:3; unsigned int f2:1; unsigned int f3:2; } foo; foo.f1 = -2; foo.f2 = 1; foo.f3 = 2; 1 … f1 f2 f3 …8 bit …
69
Notes of caution Bit-field manipulations are machine dependent
Attempting to access individual bits of a bit field as if they were elements of an array is a syntax error. Bit fields are not "arrays of bits" Attempting to take the address of a bit field (the & operator may not be used with bit fields because they do not have addresses) Although bit fields save space, using them can cause the compiler to generate slower-executing machine-language code. This occurs because it takes extra machine language operations to access only portions of an addressable storage unit.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.