首页 C语言Chapter10东北大学李丹程

C语言Chapter10东北大学李丹程

举报
开通vip

C语言Chapter10东北大学李丹程nullStructures and UnionsStructures and Unions Chapter 1010.1 Introduction10.1 IntroductionWe have seen that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However, we cannot use an array if we w...

C语言Chapter10东北大学李丹程
nullStructures and UnionsStructures and Unions Chapter 1010.1 Introduction10.1 IntroductionWe have seen that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However, we cannot use an array if we want to represent a collection of data items of different types using a single name. Fortunately, C supports a constructed data type known as structures, a mechanism for packing data of different types.10.1 Introduction10.1 IntroductionA structure is a convenient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in many other languages. 10.1 Introduction10.1 IntroductionMore example of such structures are: time : seconds, minutes, hours date : day, month, year book : author, title, price, year city : name, country, population address : name, door-number, street inventory : item, stock, value 10.1 Introduction10.1 IntroductionStructures helps to organize complex data in a more meaningful way. It is a powerful concept that we may often need to use in our program design. This chapter is devoted to the study of structures and their applications in program development.10.2 Defining a Structure10.2 Defining a StructureUnlike arrays, structures must be defined first for their format that may be used later to declare structure variables.10.2 Defining a Structure10.2 Defining a StructureConsider a book database consisting of book name, author, number of pages, and price. We can define a structure to hold this information as follows: struct book_bank{ char title[20]; char author[15]; int pages; float price; };10.2 Defining a Structure10.2 Defining a StructureThe keyword struct declares a structure to hold the details of four data fields, namely title, author, page, price. These fields re called structure elements or members. Each member may belong to a different type of data.10.2 Defining a Structure10.2 Defining a Structurebook_bank is the name of the structure and is called the structure. The tag name may be used subsequently to declare variables that have the tag’s structure.10.2 Defining a Structure10.2 Defining a StructureThe above definition describes a format called template to represent information as shown below:array of 20 charactersarray of 15 charactersintegerfloattitleauthorpagesprice10.2 Defining a Structure10.2 Defining a StructureThe general format of a structure definition is as follows:struct tag_name { data_type member1; data_type member2; … … … … };10.2 Defining a Structure10.2 Defining a StructureIn defining a structure you may note the following syntax: 1. The template is terminated with a semicolon. 2. While the entire definition is considered as a statement, each member is declared independently for its name and type in a separate inside the template.10.2 Defining a Structure10.2 Defining a Structure3. The tag name such as book_bank can be used to declare structure variables of its type, later in the program.10.2 Defining a Structure10.2 Defining a StructureArrays vs Structures Sameness: Both the array and structures are classified as structured data types as they provide a mechanism that enable us to access and manipulate data in a relatively easy manner. 10.2 Defining a Structure10.2 Defining a StructureArrays vs Structures differentia : 1. An array is a collection of related data elements of same type. Structure can have elements of different types. 2. An array is derived data type whereas a structure is a programmer-defined one. 10.2 Defining a Structure10.2 Defining a Structure3. Any array behaves like a built-n data type. All we have to do is to declare an array variable and use it. But in the case of a structure, first we have to design and declare a data structure before the variables of that type are declared and used. 10.3 Declaring Structure Variables10.3 Declaring Structure VariablesA structure variable declaration is similar to the declaration of variables of any other data types. It includes the following elements: 1.The keyword struct. 2. the structure tag name. 3.List of variable names separeted by commas 4.A terminating semicolon. 10.3 Declaring Structure Variables10.3 Declaring Structure VariablesFor example, the statement struct book_bank book1, book2, book3; declares book1, book2, book3 as variables of type struct book_bank Each one of these variables has four members as specified by the template. 10.3 Declaring Structure Variables10.3 Declaring Structure VariablesThe complete declaration might look like this: struct book_bank{ char title[20]; char author[15]; int pages; float price; }; struct book_bank book1, book2, book3; 10.2 Defining a Structure10.2 Defining a StructureRemember that the members of a structure themselves are not variable. They do not occupy any memory until they are associated with the structure variables such as book1. When the compiler comes across a declaration statement, it reserves memory space for the structure variables. 10.3 Declaring Structure Variables10.3 Declaring Structure VariablesWe can also combine both the structure definition and variables declaration together. struct book_bank{ char title[20]; char author[15]; int pages; float price; } book1, book2, book3; 10.3 Declaring Structure Variables10.3 Declaring Structure VariablesThe use of tag name is optional. struct { char title[20]; char author[15]; int pages; float price; } book1, book2, book3; is also valid.10.3 Declaring Structure Variables10.3 Declaring Structure VariablesThe above declaration declares book1, book2 and book3 as structure variables representing three books, but does not include a tag name. However, this approach is not recommended for two reasons: 1. Without a tag name, we cannot use it for future declarations.10.3 Declaring Structure Variables10.3 Declaring Structure Variables 2. Normally, structure definition appear at the beginning of the program file, before any variables or functions are defined. They may also appear before the main, along with macro definitions, such as #define. In such cases, the definition is global and can be used by other functions as well.10.3 Declaring Structure Variables10.3 Declaring Structure VariablesWe can also use the keyword typedef to define a structure as follows: typedef struct{ type member1; type member2; … } type_name;10.3 Declaring Structure Variables10.3 Declaring Structure VariablesThe type_name represents structure definition associated with it and therefore can be used to declare structure variables as shown below: type_name variable1, variable2,…;10.3 Declaring Structure Variables10.3 Declaring Structure VariablesRemember that: 1. The name type_name is the type definition name, not a variable. 2. We cannot define a variable with typedef declaration.10.4 Accessing Structure Members10.4 Accessing Structure MembersThe members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. For example, the word title, has no meaning whereas the phrase ‘title of book3’ has a meaning.10.4 Accessing Structure Members10.4 Accessing Structure MembersThe link between a member and a variable is established using the member operator ‘.’, which is also known as ‘ dot operator’ or ‘period operator.’ For example, book1.price is the variable representing the price of book1 and can be treated like any other ordinary variable.10.4 Accessing Structure Members10.4 Accessing Structure MembersHere is now we would assign values to the members of book1: strcpy(book1.title, “BASIC”); strcpy(book1.author,“Balagurusamy”); book1.pages = 250; book1.price = 120.50;10.4 Accessing Structure Members10.4 Accessing Structure MembersWe can also use scanf to give the values though the keyboard. scanf(“%s”, book1.title); scanf(“%d”, &book1.pages);10.4 Accessing Structure Members10.4 Accessing Structure MembersExample 10.1struct personal{ char name[20]; int day; char month[10]; int year; float salary; }; main(){ struct personal person; printf(“Input Values\n”);10.4 Accessing Structure Members10.4 Accessing Structure Membersscanf(“%s %d %s %d %f”, person.name, &person.day person.month, &person.year &person.salary); printf(“%s %d %s %d %f”, person.name, person.day, person.month, person.year, person.salary); }10.4 Accessing Structure Members10.4 Accessing Structure MembersOutput Input Values M.L.Goel 10 January 1945 4500 M.L.Goel 10 January 1945 4500.0010.5 Structure Initialization10.5 Structure InitializationLike any other data type, a structure variable can be initialized at compile time.main(){ struct{ int weight; float height; } student = {60,180.75}; … }Assign 60 to student.weightAssign 180.75 to student.height10.5 Structure Initialization10.5 Structure InitializationThe following statements initialize two structure variables.main(){ struct st_record{ int weight; float height; }; struct st_record student1 = {60, 180.75}; struct st_record student2 = {53, 170.0}; … }Here, it is essential to use a tag name.10.5 Structure Initialization10.5 Structure InitializationAnother method is to initialize a structure variable outside the function.struct st_record{ int weight; float height; } student1 = {60, 180.75}; main(){ struct st_record student2 = {50, 170.0}; … }10.5 Structure Initialization10.5 Structure InitializationNote that C language does not permit the initialization of individual structure members within the template. The initialization must be done only in the declaration of the actual variables.10.5 Structure Initialization10.5 Structure InitializationNote that the compile-time initialization of a structure variable must have the following elements: 1. The keyword struct. 2. The structure tag name. 3. The name of the variable to be declared. 4. The assignment operator = . 10.5 Structure Initialization10.5 Structure Initialization 5. A set of values for the members of the structure variable, separated by commas and enclosed in braces. 6. The terminating semicolon.10.5 Structure Initialization10.5 Structure InitializationThere are a few rules to keep in mind while initializing structure variables at compile-time: 1. We cannot initialize individual members inside the structure template. 2. The order of values enclosed in braces must match the order for members in the structure definition. 10.5 Structure Initialization10.5 Structure Initialization 3. It is permitted to have a partial initialization. We can initialize only the first few members and leave the remaining blank. The uninitialized members should be only at the end of the list. 4. The uninitiallized members will be assigned default values as follows: Zero for integer and floating point numbers. ‘\0’ for characters and strings.10.6 Coping and Comparing Structure Variable10.6 Coping and Comparing Structure VariableTwo variables of the same structure type can be copied the same way as ordinary variables. If person1 and person2 belong to the same structure, then the following statements are valid: person1 = person2; person2 = person1;10.6 Coping and Comparing Structure Variable10.6 Coping and Comparing Structure VariableHowever, the statements such as: person1 == person2; person1 !=person2; are not permitted. C does not permit any logical operations on structure variables. In case, we need to compare them, we may do so by comparing members individually.10.6 Coping and Comparing Structure Variable10.6 Coping and Comparing Structure VariableExample 10.2struct class{ int number; char name[20]; float mark; }; main(){ int x; struct class student1={1,”Rao”,72.1}; struct class student2={2,”Red”,67.0}; struct class student3; student3 = student2; }10.6 Coping and Comparing Structure Variable10.6 Coping and Comparing Structure Variablex = ((student3.number == student2.number) && (student3.mark == student2.mark)) ? 1:0; if(x == 1){ printf(“\nstudent2 and student3 are same.\n\n”); printf(“%d %s %f\n”, student3.number,student3.name, student3.mark); }10.6 Coping and Comparing Structure Variable10.6 Coping and Comparing Structure Variableelse { printf(“\nstudent2 and student3 are different.\n\n”); }Output student2 and student3 are same. 2, Red, 67.000000课堂练习课堂练习定义一个包含年、月、日的生日结构体BDATE。 定义一个学生基本信息的结构体student,结构体中的成员包括:学号、姓名、性别、年龄,身高,生日等。 利用上面定义的结构体,定义一个结构体数组stu,以便存储5个学生的基本信息。nullstruct BDATE { int year,month,day; }; struct student { char number[12]; char name[20]; char gender; int age; int height; struct BDATE birthday; }; struct student stu[5];10.7 Operations on Individual Members 10.7 Operations on Individual Members Example: float sum; … if(student1.number == 111){ student1.marks += 10.00; } sum = student1.marks+student2.marks; student2.marks *= 0.5;10.7 Operations on Individual Members 10.7 Operations on Individual Members We can also apply increment and decrement operators to numeric type members. Example: student1.number ++; ++ student .number; The precedence of the member operator is higher than all arithmetic and relational operators and therefore no parentheses are required.10.8 Arrays of Structures10.8 Arrays of StructuresWe use structures to describe the format of a number of related variables. In analyzing the marks obtained be a class of students, we may use a template to describe student name and marks obtained in various subjects and then declare all the students as structure variable.10.8 Arrays of Structures10.8 Arrays of StructuresIn such cases, we may declare an array of structures, each element of the array representing a structure variable. Example struct class student[100]; defines an array called student, that consists of 100 elements.10.8 Arrays of Structures10.8 Arrays of StructuresConsider the following declarations: struct marks{ int subject1; int subject2; int subject3; }; main(){ struct marks students[3] = {{45,68,81},{75,53,69},{57,36,71}};}10.8 Arrays of Structures10.8 Arrays of StructuresThis declares the student as an array of three elements student[0], student[1], student[2] and initializes their members as follows: student[0].subject1 = 45; student[0].subject2 = 68; … … student[2].subject3 = 71; 10.8 Arrays of Structures10.8 Arrays of StructuresNote that the array is declared just as it would have been with any other array. Since student is an array, we use the usual array-accessing methods to access individual elements and then the member operator to access members. Each element of student array is a structure variable with three members.10.8 Arrays of Structures10.8 Arrays of Structuresstudent[0].subject1student[2].subject1student[1].subject1subject2subject2subject2subject3subject3subject310.8 Arrays of Structures10.8 Arrays of StructuresExample:struct marks{ int sub1; int sub2; int sub3; int total; }; main(){ int i; struct marks student[3]={ {45,67,81,0},{75,53,69,0}, {57,36,71,0}}; struct marks total;10.8 Arrays of Structures10.8 Arrays of Structuresfor(i = 0; i <= 2;i++){ student[i].total = student[i].sub1 + student[i].sub2 + student[i].sub3; total.sub1=total.sub1+student[i].sub1; total.sub2=total.sub2+student[i].sub2; total.sub3=total.sub3+student[i].sub3; total.total=total.total+student[i].total; } printf(“STUDENT TOTAL\n\n”); for(i = 0; i <= 2;i++) printf(“Student[%d] %d\n”, i+1, student[i].total);10.8 Arrays of Structures10.8 Arrays of Structuresprintf(“\n SUBJECT TOTAL\n\n”); printf(“%s %d\n%s %d\n %s %d\n”, “Subject 1 “, total.sub1 “Subject 2 ”, total.sub2 “Subject 3 ”, total.sub3); printf(“\nGrand Total = %d\n”,total.total);10.8 Arrays of Structures10.8 Arrays of StructuresOutput STUDENT TOTAL Student[1] 193 Student[2] 197 Student[3] 164 SUBJECT TOTAL Subject 1 177 Subject 2 156 Subject 3 221 Grand Total = 554 10.9 Arrays within Structures10.9 Arrays within StructuresC permits the use of arrays as structure members. Example: struct marks{ int number; float subject[3]; } student[2];10.9 Arrays within Structures10.9 Arrays within StructuresHere, the member subject contains three elements, subject[0], subject[1] and subject[2]. These elements can be accessed using appropriate subscripts. Example: student[1].subject[2]; would refer to the marks obtained in the third subject by the second student.10.9 Arrays within Structures10.9 Arrays within StructuresExample:main(){ struct marks{ int sub[3]; int total; }; struct marks student[3]= {45,67,81,0,75,53,69,0,57,36,71,0}; struct marks total; int i, j;10.9 Arrays within Structures10.9 Arrays within Structuresfor(i = 0;i <= 2;i++){ for(j = 0; j <=2;j++){ student[i].total+=student[i].sub[j]; total.sub[j]+=student[i].sub[j]; } total.total += student[i].total; } printf(“STUDENT TOTAL\n\n”); for(i = 0;i<=2;i++) printf(“Student[%d] %d”,i+1,student[i].total);10.9 Arrays within Structures10.9 Arrays within Structuresprintf(“\nSUBJECT TOTAL\n\n”); for(j = 0;j <= 2;j++) printf(“Subject-%d %d\n”,j+1,total.sub[j]); printf(“\nGrand Total = %d\n”,total.total);10.9 Arrays within Structures10.9 Arrays within StructuresOutput STUDENT TOTAL Student[1] 193 Student[2] 197 Student[3] 164 SUBJECT TOTAL Subject-1 177 Subject-2 156 Subject-3 221 Grand Total = 55410.10 Structures within Structures10.10 Structures within StructuresStructures within a structure means nesting of structures. Nesting of structure is permitted in C.10.10 Structures within Structures10.10 Structures within StructuresExample: struct salary{ char name; char department; int basic_pay; int dearness_allowance; int house_ret_allowance; int city_allowance; } employee;10.10 Structures within Structures10.10 Structures within StructuresThe structure defines name, department, basic pay and three kinds of allowances. We can group all the items related to allowance together and declare them under a substructure as shown next page:10.10 Structures within Structures10.10 Structures within Structures struct salary{ char name; char department; struct{ int dearness; int house_rent; int city; } allowance; } employee;10.10 Structures within Structures10.10 Structures within StructuresThe salary structure contains a member allowance which itself is a structure with three members. The members contained in the inner structure can be referred to as: employee.allowance.dearness employee.allowance.house_rent employee.allowance.city10.10 Structures within Structures10.10 Structures within StructuresAn inner-most member in a nested structure can be accessed by chaining all the concerned structure variables. The following are invalid: employee.allowance NO employee.house_rent NO 10.10 Structures within Structures10.10 Structures within StructuresAn inner structure can have more than one variable. struct salary{ … struct{ int dearness; … } allowance, arrears; } employee[100];10.10 Structures within Structures10.10 Structures within StructuresThe inner structure has two variables, allowance and arrears. This implies that both of them have the same structure template. A base member can be accessed as follows: employee[1].allowance.dearness employee[1].arrears.dearness 10.10 Structures within Structures10.10 Structures within StructuresWe can also use tag names to define inner structures: struct pay{ int dearness; int house_rent; int city;}; struct salary{ char name; char department; struct pay allowance; struct pay arrears;}; struct salary employee[100];10.10 Structures within Structures10.10 Structures within StructuresIn this example pay template is defined outside the salar
本文档为【C语言Chapter10东北大学李丹程】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_740234
暂无简介~
格式:ppt
大小:500KB
软件:PowerPoint
页数:0
分类:互联网
上传时间:2011-01-14
浏览量:8