




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
Chapter10Structures,Unions,Enumerations10.1Introduction10.2 StructureDefinitions結構體聲明10.3 InitializingStructures初始化結構體10.4 AccessingMembersofStructures10.5 UsingStructureswithFunctions函數中使用結構體10.6 ArrayofSructures
結構體數組10.7 typedef10.8 Example:High-PerformanceCardShufflingandDealingSimulation10.9Unions10.10EnumerationConstantsOutlineStructureDefinitions結構體聲明InitializingStructures初始化結構體AccessingMembersofStructures結構體變量的引用UsingStructureswithFunctions結構體與函數typedefArrayofSructures
結構體數組KeyPoints10.1IntroductionWhyneed“Structure”?Sofar,we’ddiscussedtwokindsofdata:Simple:char,int,long,double,etc.Scalar:array,pointer,etc.It’sinconvenientinsomeapplications:Seenextslidesforanexample10.1IntroductionWewanttorepresenttimeasyear/month/date:intf(){intyear1,year2,month,date;year1=2050;year2=2020;month=12;date=30;date++;/*Shouldweincreaseyear1oryear2?*/}Theproblemisthatthereisnologicalconnectionbetweenthem.Weneed“structure”!10.1IntroductionStructuresCollectionsofrelatedvariables(aggregates)underonename
多個相關變量的集合,且擁有同一個變量名CancontainvariablesofdifferentdatatypesCommonlyusedtodefinerecordstobestoredinfilesCombinedwithpointers,cancreatelinkedlists,stacks,queues,andtrees--將結構體和指針結合,可構造鏈表、棧、隊列、樹10.1IntroductionStructureStructureisaadvanceddatatypeinC.結構體是C中的高級數據類型Structureisamethodforgroupingaseveralrelateddatatypetogether.結構體是將一些相關聯的數據整合成整體的一種方法。Variableswithdifferenttypescanbegroupedinastructure。不同類型的變量可以組合在一個結構體內。Thesimplevariables:inta,b;a=20,b=85;-invidual
Array:floatgrade[20];
sametyperelatedgrade[0]grade[1]grade[2]grade[3]……10.1Introductionnumnamegrade1grade210Li90.5A11Liu80B12Wen88B….
intcharfloatchar
Howcanwedefinerelateddatathathavedifferenttype?
struct{intnum;charname[10];floatgrade1;chargrade2;};10.1IntroductionAllvariableswiththesametypescanbegroupedinaarray.wang98889887li87668367zhan78877561liu90768172zhao87817471Allvariableswithdifferenttypescanbegroupedinastructurenameagesexaddwang18m3-110li20f7-121liu17f7-212zhao18m3-222structuremembers(type,name)Structurevariables10.2StructureDefinitions1
32Astructureisacollectionofrelatedvariables,anynumberoftypeofvariablesmaybeincludedwithinit.Definingstructure,thendeclaringstructvariables.Definingstructureandstructvariables.structure’snamecanbeomittedkeywordstructStructuremembers
SturcturevariablesStructurevariablevalues10.2StructureDefinitionsDefiningstructure,thendeclaringstructvariables.先聲明結構體,再聲明結構體變量。
structstudent{intnum;charname[10];floatgrade1;chargrade2;};Structureisonlyasstructuretemplate,notoccupyingmemory,becausenoanyvariableyet.—聲明結構體時,并不占用內存空間。numnamegrade1grade2structname
{type1member1;type2member2;︰typenmembern;};(1)Definingstructure
10.2StructureDefinitionsstructdata{charname[20];intage;charaddress[30];longtelephone;};Formal:structstruct_namestruct_variable_name;structdatawang;structdatali,zhang;(2)Declaringstructurevariable
nameageaddresstelephone10.2StructureDefinitionsname[20]
age20bytes2bytes30bytes4bytesaddresstelephonename[20]ageaddress[30]telephonestructdata{charname[20];intage;charaddress[30];longtelephone;};structdatawang;Afterdeclaration,computerwillassignmemoryunitstothem.–在結構體變量聲明后,計算機將給變量分配內存空間10.2StructureDefinitions
main(){charstr[20];
structdate{intyear,month,day;}today;
structaddress{charname[30],street[40],city[20],state[2];unsignedlongintzip;}wang;
printf("char:%d\t",sizeof(char));printf(“int:%d\t”,sizeof(int));printf("long:%d\t",sizeof(long));printf("float:%d\n",sizeof(float));printf("double:%d\t",sizeof(double));printf("str:%d\t",sizeof(str));printf("date:%d\t",sizeof(structdate));printf(“wang:%d\n”,sizeof(wang));}10.2StructureDefinitionsDefiningstructureandstructvariables.聲明結構體的同時,聲明結構體變量structname{type1member1;type2member2;︰typenmembern;}variable1,variable2…..;
structstudent{intnum;charname[20];charsex;intage;floatscore;charaddr[30];}stu1,stu2;numnamesexagescoreaddstu1stu210.2StructureDefinitionsstructure’snamecanbeomittedstruct{type1member1;type2member2;︰typenmembern;}variable1,variable2…..;
struct{intnum;charname[20];charsex;intage;floatscore;charaddr[30];}stu1,stu2;numnamesexagescoreaddr201wangM2095Zhongguancunroad202liF1980GuangdaGarden10.3InitializingStructures
structstudent{intnum;charname[20];charsex;intage;charaddr[30];}stu1={112,“WangLin”,‘M’,19,“200BeijingRoad”};
structstudent{intnum;charname[20];charsex;intage;charaddr[30];}stu1;stu1={112,“WangLin”,‘M’,19,“200BeijingRoad”};Howtousethesevalues?10.4AccessingMembersofStructuresstud1.grade1=95;stud1.grade2=‘A’;where“.”iscalled
memberoperator.struct_var_name.member_name
struct{intnum;charname[10];floatgrade1;chargrade2;}stud1,stud2,stud3;scanf(“%s,%f,%c,”,&,&stud2.grade1,&stud2.grade2);printf(“%s,%f,%c,”,,stude2grade1,stude2grade2);10.4AccessingMembersofStructures/*assignment*/main(){struct{charinitial;/*lastnameinitial*/intage;/*childsage*/intgrade;/*childsgradeinschool*/}boy,girl;boy.initial='R';boy.age=17;boy.grade=75;
girl.age=boy.age-1;/*sheisoneyearyounger*/girl.grade=82;girl.initial='H';printf("%cis%dyearsoldandgotagradeof%d\n",girl.initial,girl.age,girl.grade);printf("%cis%dyearsoldandgotagradeof%d\n",boy.initial,boy.age,boy.grade);}10.4AccessingMembersofStructuresOworkaddressHomeaddresspostaddrtelpostaddrtelstructaddress{intpostcharaddr[100];chartel[20];};structpersonal{charname[20];structaddressworkaddr;structaddresshomeaddr;};struct_var_name.out_mem.inner_mem10.4AccessingMembersofStructuresmain(){structdate{/*structuretypedate*/intyear,month,day;
};structdatetoday;/*stru-vartoday*/printf("Entertodaydate:");scanf(“%d%d%d”,&today.year,&today.month,&today.day);printf(“%d.%d.%d\n”,today.year,today.month,today.day);}date&today.daytoday.day10.4AccessingMembersofStructuresExercise:
structstudent{intnocharname[20];charsex;struct
{intyear;intmonth;intday;}birth;};structstudents;A)year=1982month=11day=11B)birth.year=1982,birth.month=11birth.day=11C)s.year=1982s.month=11s.day=11D)s.birth.year=1982s.birth.month=11s.birth.day=11
Ifthebirthdayis“11/11
/82”,whichisthecorrectassignmentstatement?10.5UsingStructuresWithFunctionsPassingstructurestofunctionsPassentirestructureOr,passindividualmembersBothpasscallbyvalueTopassstructurescall-by-reference
PassitsaddressPassreferencetoitTopassarrayscall-by-valueCreateastructurewiththearrayasamemberPassthestructure10.5UsingStructuresWithFunctionsStructurememberasargumentstructxscj{char*xh;floatcj[2];floatav;};main(){structxscjxs={"01",70,80},inti;xs.av=ave(xs.cj[0],xs.cj[1]);printf("%s,%5.1f,%5.1f,%5.1f\n",xs.xh,xs.cj[0],xs.cj[1],xs.av);}}ave(floatx,floaty){floata;a=(x+y)/2.0;returna;}01,70.0,80.0,75.002,78.0,67.0,72.503,56.0,78.0,67.004,90.0,80.0,85.010.5UsingStructuresWithFunctionsStructureasargumentstructxscj{char*xh;floatcj[2];floatav;};voidf1(structxscjtj);main(){structxscjxs={"01",70,80,0};f1(xs);}
voidf1(structxscjtj){tj.av=(tj.cj[0]+tj.cj[1])/2.0;printf("%s,%5.1f,%5.1f,%5.1f\n",tj.xh,tj.cj[0],tj.cj[1],tj.av);}output01,70.0,80.0,75.010.6ArrayofSructures
DefinitionForm1
structstudent{intnum;charname[20];charsex;intage;};structstudentstu[30];Form2
structstudent{intnum;charname[20];charsex;intage;}stu[30];Form3
struct{intnum;charname[20];charsex;intage;}stu[30];Array–groupseveralrelatedvariableswiththesametype,storeinsequence30studentsInoneclassThetypeisstructure10.6ArrayofSructures
TherelationshipbetweenstructureandarrayArrayisamemberofastructureAnarraywhichmembersareallstructurevariablenumNameScore[0]Score[1]101wang9098110zhan8775struct{intnum;
charname[20];floatscore[2];}stu1,stu2;numNameScore[0]Score[1]101wang9098110zhan8775struct{intnum;
charname[20];floatscore[2];}stu[2];10.6ArrayofSructures
Initualizationstructstud{intxh;......};structstudxscj[3]={{},{},{}};
OR:structstud{intxh;......}xscj[3]={{},{},{}};Datainonearray10.6ArrayofSructures
Accessmembersofstructurearraymain(){structxscjxs[4]={{"01",70,80},{"02",78,67},{"03",56,78},{"04",90,80}};inti;for(i=0;i<4;i++){xs[i].av=(xs[i].cj[0]+xs[i].cj[1])/2.0;printf("%s,%5.1f,%5.1f,%5.1f\n",xs[i].xh,xs[i].cj[0],xs[i].cj[1],xs[i].av);}}structxscj{char*xh;floatcj[2];floatav;};structurearraymemberofstructurememberofthearrayoutput01,70.0,80.0,75.002,78.0,67.0,72.503,56.0,78.0,67.004,90.0,80.0,85.010.6ArrayofSructures
Afterdeclaration,howtooutput‘M’?structperson{charname[9];
intage;};structpersonclass[10]={“Wang”,17,“Zhang”,19,“Ming”,18,“Liu”,20};A)printf(“%c\n”,class[3].name);B)printf(“%c\n”,class[3].name[1]);C)printf(“%c\n”,class[2].name[1]);D)printf(“%c\n”,class[2].name[0]);MemberofarrayMemberofstructurearray10.7typedeftypedefCreatessynonyms(aliases)forpreviouslydefineddatatypesUsetypedeftocreateshortertypenamesExample:typedefstructCard*CardPtr;DefinesanewtypenameCardPtrasasynonymfortypestructCard*typedefdoesnotcreateanewdatatypeOnlycreatesanalias10.7typedefDefinitethealiasofstructurestructdateasDATE.structdate{intyear,month,day;};typedefstructdateDATE;DATAt,*p;
equalto:typedefstructdate
{intyear,month,day;}DATE;DATAt,*p;Onlycreatesanalias.10.7typedefDemonstration(說明):
Todefiniteanaliastoaexistvariableusingtypedefwon’tcreatanewtype.Differencebetweentypedefand#define.typedefisdisposingwhencompiling;#defineisdispoingwhenpreprocessing,asacounterpart10.8Example統(tǒng)計十佳運動員選票,在統(tǒng)計之前要將預選的運動員名字賦給相應的name數組,同時將每個人的選票計數器清零。structports{char*name;intcount;}x[]={"LiNing",0,"LangPing",0,"ZhuJianHua",0,"LanJuJie",0};main(){inti;for(i=0,i<=3;i++)printf("%s:%d\n",x[i].name,x[i].count);
}10.8Example簡單的加密程序??啥x一個結構table的成員in,存入輸入的字符,out輸出加密后的字符。輸入(in):abcdefghijkwxy輸出(out):cdfahikxywbgje#include〈stdio.h〉structtable{charin;charout;};structtabletrans[]={’a’,’c’,’b’,’d’,’c’,’f’,’d’,’a’,’e’,’h’,’f’,’i’,’g’,’k’,’h’,’x’,’i’,’y’,’j’,’w’,‘k’,’b’,’v’,’g’,’x’,’j’,’y’,’e’};
10.8Examplemain(){charch;intstrlong,i;strlong=sizeof(trans)/sizeof(structtable);while((ch=getchar())!=‘\n’){for(i=0;trans[i].in!=ch&&i<strlong;i++); if(i<strlong)putchar(trans[i].out);elseputchar(ch);}}10.9UnionsunionMemorythatcontainsavarietyofobjectsovertimeOnlycontainsonedatamemberatatimeMembersofaunionsharespaceConservesstorageOnlythelastdatamemberdefinedcanbeaccesseduniondeclarationsSameasstructunionNumber{intx;floaty;};unionNumbervalue;10.9UnionsValidunionoperationsAssignmenttounionofsametype:=Takingaddress:&Accessingunionmembers:.Accessingmembersusingpointers:->1.Defineunion1.1Initializevariables2.Setvariables3.Print 1 /* 2
Anexampleofaunion*/ 3 #include<stdio.h> 4 5 unionnumber{ 6
intx; 7
doubley; 8 }; 9 10 intmain() 11 { 12
unionnumbervalue; 13
14
value.x=100; 15
printf("%s\n%s\n%s%d\n%s%f\n\n", 16 "Putavalueintheintegermember", 17 "andprintbothmembers.", 18 "int:",value.x, 19 "double:\n",value.y); 20
21
value.y=100.0; 22
printf("%s\n%s\n%s%d\n%s%f\n", 23 "Putavalueinthefloatingmember", 24 "andprintbothmembers.", 25 "int:",value.x, 26 "double:\n",value.y); 27
return0; 28 }
P:100double:-92559592117433136000000000000000000000000000000000000000000000.00000
P:0double:100.000000ProgramOutput10.10EnumerationConstantsEnumerationSetofintegerconstantsrepresentedbyidentifiersEnumerationconstantsarelikesymbolicconstantswhosevaluesareautomaticallysetValuesstartat0andareincrementedby1Valuescanbesetexplicitlywith=NeeduniqueconstantnamesExample:enumMon
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 農民致富種植策略方案
- 農業(yè)技術推廣區(qū)域合作方案
- 中國污水處理行業(yè)報告
- 制藥行業(yè)生物制藥工藝優(yōu)化方案
- 辦公室裝修風險免責協議
- 垃圾焚燒發(fā)電股
- 電信行業(yè)網絡優(yōu)化與安全防護策略方案
- 項目可行性研究報告指南
- 季度營銷活動策劃方案
- 汽車銷售與服務營銷策略試題
- 人教版2024-2025學年數學八年級下學期 16.2二次根式的乘除法同步練習【基礎練】(含答案)
- 2025年山東省職教高考《英語》高頻必練考試題庫400題(含答案)
- 2025高考誓師大會校長講話:最后100天從“青銅”逆襲成“王者”
- 2024-2025學年第二學期國旗下講話稿及安排
- 2025年安徽審計職業(yè)學院單招職業(yè)適應性測試題庫有答案
- 2024年甘肅省白銀市中考數學試卷(附答案)
- 煤礦機電維護工職業(yè)技能理論考試題庫150題(含答案)
- 《黑格爾哲學思想》課件
- 老年骨質疏松性疼痛診療與管理中國專家共識2024解讀課件
- 金光修持法(含咒訣指印、步驟、利益說明)
- 新國標《出版物上數字用法》操作要點解析范文
評論
0/150
提交評論