




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Chapter10Structures,Unions,Enumerations10.1Introduction10.2 StructureDefinitions結(jié)構(gòu)體聲明10.3 InitializingStructures初始化結(jié)構(gòu)體10.4 AccessingMembersofStructures10.5 UsingStructureswithFunctions函數(shù)中使用結(jié)構(gòu)體10.6 ArrayofSructures
結(jié)構(gòu)體數(shù)組10.7 typedef10.8 Example:High-PerformanceCardShufflingandDealingSimulation10.9Unions10.10EnumerationConstantsOutlineStructureDefinitions結(jié)構(gòu)體聲明InitializingStructures初始化結(jié)構(gòu)體AccessingMembersofStructures結(jié)構(gòu)體變量的引用UsingStructureswithFunctions結(jié)構(gòu)體與函數(shù)typedefArrayofSructures
結(jié)構(gòu)體數(shù)組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
多個(gè)相關(guān)變量的集合,且擁有同一個(gè)變量名CancontainvariablesofdifferentdatatypesCommonlyusedtodefinerecordstobestoredinfilesCombinedwithpointers,cancreatelinkedlists,stacks,queues,andtrees--將結(jié)構(gòu)體和指針結(jié)合,可構(gòu)造鏈表、棧、隊(duì)列、樹10.1IntroductionStructureStructureisaadvanceddatatypeinC.結(jié)構(gòu)體是C中的高級(jí)數(shù)據(jù)類型Structureisamethodforgroupingaseveralrelateddatatypetogether.結(jié)構(gòu)體是將一些相關(guān)聯(lián)的數(shù)據(jù)整合成整體的一種方法。Variableswithdifferenttypescanbegroupedinastructure。不同類型的變量可以組合在一個(gè)結(jié)構(gòu)體內(nèi)。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.先聲明結(jié)構(gòu)體,再聲明結(jié)構(gòu)體變量。
structstudent{intnum;charname[10];floatgrade1;chargrade2;};Structureisonlyasstructuretemplate,notoccupyingmemory,becausenoanyvariableyet.—聲明結(jié)構(gòu)體時(shí),并不占用內(nèi)存空間。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.–在結(jié)構(gòu)體變量聲明后,計(jì)算機(jī)將給變量分配內(nèi)存空間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.聲明結(jié)構(gòu)體的同時(shí),聲明結(jié)構(gòu)體變量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(說(shuō)明):
Todefiniteanaliastoaexistvariableusingtypedefwon’tcreatanewtype.Differencebetweentypedefand#define.typedefisdisposingwhencompiling;#defineisdispoingwhenpreprocessing,asacounterpart10.8Example統(tǒng)計(jì)十佳運(yùn)動(dòng)員選票,在統(tǒng)計(jì)之前要將預(yù)選的運(yùn)動(dòng)員名字賦給相應(yīng)的name數(shù)組,同時(shí)將每個(gè)人的選票計(jì)數(shù)器清零。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簡(jiǎn)單的加密程序??啥x一個(gè)結(jié)構(gòu)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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 鷹潭職業(yè)技術(shù)學(xué)院《視覺(jué)包裝》2023-2024學(xué)年第一學(xué)期期末試卷
- 調(diào)度證考試試題及答案
- 電網(wǎng)保命考試試題及答案
- 電工證試題及答案
- 電工操作考試試題及答案
- 電廠安全資質(zhì)考試試題及答案解析
- 初中化學(xué)單元測(cè)試題及答案
- 山西能源學(xué)院《大學(xué)書法》2023-2024學(xué)年第一學(xué)期期末試卷
- 湖北省隨州市曾都區(qū)實(shí)驗(yàn)中學(xué)2024年七上數(shù)學(xué)期末調(diào)研試題含解析
- 江蘇工程職業(yè)技術(shù)學(xué)院《信息系統(tǒng)項(xiàng)目管理》2023-2024學(xué)年第一學(xué)期期末試卷
- DB37-T5311-2025建筑工程消防設(shè)計(jì)文件編制標(biāo)準(zhǔn)
- 成都市高新區(qū)2023年七年級(jí)《歷史》下冊(cè)期末試卷與參考答案
- 中國(guó)上市銀行2024年回顧及未來(lái)展望-安永-202505
- TSG Z7002-2022特種設(shè)備檢測(cè)機(jī)構(gòu)核準(zhǔn)規(guī)則
- 裝修售后維修合同協(xié)議
- 2025年數(shù)字經(jīng)濟(jì)下的創(chuàng)業(yè)政策調(diào)整策略試題及答案
- 第30課 在線安全防范-2024-2025學(xué)年三年級(jí)全一冊(cè)《信息技術(shù)》教案
- 政治 (道德與法治)八年級(jí)下冊(cè)自由平等的追求教案
- 山東省濟(jì)南市高新區(qū)學(xué)卷B2024-2025學(xué)年數(shù)學(xué)五下期末教學(xué)質(zhì)量檢測(cè)試題含答案
- 訂單外發(fā)合同協(xié)議
- 山東省2024年藝術(shù)類本科批音樂(lè)類第1次志愿投檔情況表(公布)
評(píng)論
0/150
提交評(píng)論