版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
chapter10STRUCTURESANDUNIONSAstructureisacollectionofoneormorevariables,possiblyofdifferenttypes,whicharetreatedasaunitinsteadofasseparateentities.10.1structuredefinition
10.2
structurevariablescitingandinitialization10.3structurearray10.4structurepointer10.5
linkdispoing---applicationofstructurepointer10.6unionandenumeration10.7typedef10.1STRUCTURETYPEANDDECLARATIONOFSTRUCTUREVARIABLESTHESTRUCTURETYPE,INCLANGUAGE
,isthecounterpartas“record”inotheradvancedlanguage.一、questionemergingSTUDENTSCORESMANAGETABLE
CANOTDEALWITH2DARRAYSDIFFERENTTYEPES!1001ZhangXinM2087911002WangLiF2098961003ChenFongM2186901004LiXiaopenM207786
numnamesexagescore1score2二、structuretypedeclarationCommonusage:structstructuretypename
{
datatypemember1;
datatypemember2;
…………
datatype
membern;
};
structstudent{intnum;charname[20];charsex;
intage;floatscore1;floatscore2;};Typename
numnamesexagescore1score2structstudentdemonstration:1、therulestoname“structuretypename”and“membername”,aresamewiththevariables’.2、thedefinitionsofvariablescanbeseperatedorinasamelineliketheinstancebelow
eg.
structdate{intyear,month,day;};3、thedefinitionsofvariablescouldbebasictypesoranotherstructuretypewhichhasbeendeclarated.
eg.the
type”birthday”intheeg.Ofstructuretypestd_infoisadefinitedstructuretype--date三、
STRUCTUREVARIABLESDECLARATIONStructuretype(userdefinition)Standarttype(systemdefinition)1、indirectdeclaration
──firstdeclarethestructuretype,thenthestructurevariablesThesameusagestruct
student{intnum;charname[20];charsex;
intage;floatscore1;floatscore2;};structstudentstu1,stu2;
numnamesexagescore1score2stu12、directdeclaration(1)definitethestructurevariable,when
definitingthestructuretype;
(2)definitethestructurevariabledirectly;(1)struct
student{intnum;charname[20];……floatscore2;}stu1,stu2;(2)struct{intnum;charname[20];……floatscore2;}stu1,stu2;3、demonstration(1)differstructuretypeandvariable,whicharecompletelydifferentconception,justastypeintandvariableofint(2)membernamesinstructure,maybesameasothervariablesinprogram,standfordifferentobjects
[eg10.1]creatastructurerefferingtobasicinformationofastudenttostorethedetailsofastudentstructdate /*datastructuretypemadeofyear,monthandday*/{intyear;
intmonth;
intday;};structstd_info /*studentinformationstructuretype*/{intnum;/*madeofname,sex,birthday,etc*/charname[12];charsex;
structdatebirthday;floatscore1,score2;};numnamesexscore1score2
birthdayyearmonthday10.2CITINGAND
INITIALIZATIONSOF
STUCTUREVARIABLES
[例10.2]makeuseoftheformerstucturetypestructstd_info,todefiniteastructuretypestutostoreandprintthestudentdetails#include“struct.h”
structstd_infostu
={1002,”ZhangSan”,‘M’,{1980,9,20},98.2,86.5};
main()
{printf("No:%d\n",stu.num);
printf("Name:%s\n",);
printf("Sex:%c\n",stu.sex);
printf("Birthday:%d-%d-%d\n",stu.birthday.year,
stu.birthday.month,stu.birthday.day);}
numnamesexscore1score2
birthdayyearmonthdayresult:No:1002Name:ZhangSanSex:MBirthday:1980-9-20
1、INITIALIZATIONSOF
STUCTUREvariable
structtype
struct_variable={initialvalue
list}eg,structstd_infostu
={“000102”,”ZhangSan”,‘M’,{1980,9,20}};
note:datatypeofinitialvalueshouldbeconsistentwiththemembersinstructurevariable,ortherewillbeerror.2、citingrulesofstructurevariablememberoperator“.”whilecitingthememberinstructure,useoperator”.”;citingformat:structure
variable.member
eg,stu.num;
,etc。NOTE:ifamemberitselfisastructuretype,amultilevelmemberoperationisneededtocitethelowestmember.Expandingformat:
structurevariable.member.child-member.….LowestmemberEg.:
stu.birthday.year
stu.birthday.month
stu.birthday.daybetakingthelowestmemberisequaltocommonvariableofthesametype.10.3STRUCTUREARRAYSStructurearrays:anarraymadebystructuretypedatawhichisaselementinstructure.Everyarrayelement:includeallmembersofstructure[例10.3]usestructurearraytostoreandprintthestudentscoresmanagetablebelow.stu[0]stu[1]stu[2]stu[3]1001ZhangXinM2087911002WangLiF2098961003ChenFongM2186901004LiXiaopenM207786
numnamesexagescore1score2struct
student/*laythedefinitionofstructuretypeoutsidefunction*/{intnum;charname[12];charsex;
intage;floatscore1;floatscore2;};struct
stdentstu[4]={{1001,”ZhangXin”,’M’,20,87,91},
{1002,”WangLi”,‘F’,20,98,96},{1003,”ChenFong”,’M’,21,86,90},{1004,”LiXiaopen”,‘M’,20,77,86}};Storeinfile“struct.h”#include"struct.h”main(){inti;/*printlisthead,"□“standsforonebackspace*/printf("No.□□Name□□□□□□□□Sex□Age□soc1□sco2\n");/*outputbasicdetailsof4students*/for(i=0;i<4;i++){printf("%-5d",stu[i].num);printf("%-12s",stu[i].name);printf("%-4c",stu[i].sex);printf("%-4d",stu[i].age);printf("%-5.1f",stu[i].score1);printf("%-5.1f\n",stu[i].score2);}}Runningresult:
No.NameSexAgesoc1sco21001ZhangXinM208791
1002WangLiF2098961003ChenFongM2186901004LiXiaopenM207786[eg10.4]usearraysofstructureasfuntionparameters#include"struct.h"voidprint_stulist(structstudentstu[]){inti;
printf("No.NameSexAgesoc1sco2\n");for(i=0;i<4;i++){printf("%-5d",stu[i].num);printf("%-12s",stu[i].name);printf("%-4c",stu[i].sex);printf("%-4d",stu[i].age);printf("%-5.1f",stu[i].score1);printf("%-5.1f\n",stu[i].score2);}}UseArrayofstructureasformalparametervoidsort(structstudentst[]){inti,j;
structstudenttemp;for(i=0;i<4-1;i++)for(j=i+1;j<4;j++) if(st[i].score1<st[j].score1) {temp=st[i];
st[i]=st[j];
st[j]=temp; }}
main(){clrscr();
print_stulist(stu);
sort(stu);
printf("listaftersorted:\n");print_stulist1(stu);
getch();}Structurearrayasformalparameter
Runningresult:
No.NameSexAgesoc1sco21001ZhangXinM2087911002WangLiF2098961003ChenFongM2186901004LiXiaopenM207786listaftersorted:No.NameSexAgesoc1sco21002WangLiF2098961001ZhangXinM208791
1003ChenFongM2186901004LiXiaopenM20778610.4pointerpointedtodatatypeofstructurePointerofstructurevariable:structurevariableexistsinthestartingpositionofthestorage.voidprint_stulist(structstudentstu[]){inti;
printf("No.NameSexAgesoc1sco2\n");for(i=0;i<4;i++){printf("%-5d",stu[i].num);printf("%-12s",stu[i].name);printf("%-4c",stu[i].sex);printf("%-4d",stu[i].age);printf("%-5.1f",stu[i].score1);printf("%-5.1f\n",stu[i].score2);}}modify!Usepointerwhichpointtostructureasformalparameter
[eg10.5]usepointertocallmemberofthestructurevariablevoidprint_stulist1(structstudent*p){inti;
printf("No.NameSexAgesoc1sco2\n");for(i=0;i<4;i++){printf("%-5d",(*(p+i)).num);printf("%-12s",(*(p+i)).name);printf("%-4c",(*(p+i)).sex);printf("%-4d",(*(p+i)).age);printf("%-5.1f",(*(p+i)).score1);printf("%-5.1f\n",(*(p+i)).score2);}Ifusefor(i=0;i<4;i++,p++),thenhowtomodify?
[eg10.5]usepointertocalleverymemberofthestructurevariable
voidprint_stulist1(structstudent*p){inti;
printf("No.NameSexAgesoc1sco2\n");for(i=0;i<4;i++,p++){printf("%-5d",(*p).num);printf("%-12s",(*p).name);printf("%-4c",(*p).sex);printf("%-4d",(*p).age);printf("%-5.1f",(*p).score1);printf("%-5.1f\n",(*p).score2);}Ifthepointerhasbeenpointingtostructurevariablev,thenwhen:
structstudentvar,*p=&v;The3formsbelowareequal:
(1)var.membername(2)(*p).membername(3)p->membernamethoughts:howtoinputeverymemberofstu[i]bykeyboard?10.5linklist
disposing──applicationofstructurepointer10.5.1linklistoverview
一.Dynamicdatastructure
elementnumberfluctuatesbyprogramrunning.cf.datastructureofstaticstate(eg.array),confirmingitssizewhendefiniting.二.Dynamicdatastructureimplement
invirtueof
:
1、pointerpointstostructuretype2、structuretypeincludingpointerdata
linklist:asimpledynamicdatastructure.head
3125NULL10.5.2creatinglinklist
一、descriptionoflinklistnodestructureeg.
structnode{intnum; /*dataarea*/
structnode
*next; /*pointerarea*/};二、
functionofdisposinglinklist1、malloc——applymemorystoragevoid*malloc(unsigned
intsize)
eg.
structnode*p;p=(structnode*)malloc(sizeof(structnode));
numnextp2、free——setstorageareafreevoidfree(void*p)
三、createlinklist[例10.6]accordingtoaseriesofnonnegative
integers,inputbykeyboard,tocreatealinklist,andoutputthevalueofeverydataareabyordereg:input13250,createlinklistsuchas:3125NULLhead
1
325NULLhead/*1.creatnewnode,pointedbyheadpointer*/head=(structnode*)malloc(LEN);last=head;/*tailpointerpointstonodeoftail*/head
last/*2.inputx;createnewnodep;storextonumareaofnodep*/scanf("%d",&x);p=(structnode*)malloc(LEN);p->num=x;/*3.addptothelinklisttail*/last->next=p;
1headlastp
1headplast/*4.lastmovebackwards*/last=p;1headlastpRepeat2~4,whenx≤0
132head5NULLlast/*setpointerareaNULLwhichwaspointedbytailnodepointer,headpointermovebackwards(deletingheadnode)*/last->next=NULL;head=head->next;main(){structnode*head,*p,*last;
intx;head=(structnode*)malloc(LEN);last=head;
while(1){scanf("%d",&x);if(x<=0)break;p=(structnode*)malloc(LEN); p->num=x; last->next=p; last=p;}last->next=NULL;head=head->next;
#defineNULL0#defineLEN
sizeof(structnode)structnode{intnum;
structnode*next;};p=head;head=head->next;free(p);
132head5NULL/*outputlinklist*/printf(“dataofthelinklistare:”)p=head;while(p!=NULL){printf("%5d",p->num); p=p->next;}
printf("\n");
getch();}Runningresult:13250dataofthelinklistare:1325Q:make2functionsforcreatinglinklistandoutputlinklist:1.structnode*creat(void)2.voidprint(structnode*head)structnode*creat(void)/*createlinklistfunction*/{structnode*head,*p,*last;
intx;head=(structnode*)malloc(LEN);last=head;while(1){scanf("%d",&x);if(x<=0)break;p=(structnode*)malloc(LEN);p->num=x; last->next=p; last=p; }last->next=NULL;p=head;head=head->next;free(p);return(head);}
2、outputlinklist1、installlinklist四、realizingbyfunction:voidprint(structnode*head)/*outputlinklistfunction*/{structnode*p;
p=head;while(p!=NULL)/*traversingthelinklist*/{printf("%5d",p->num); p=p->next;}
printf("\n");getch();}main(){structnode*head;
printf("inputdatatocreat
linklist(endby<=0):\n");head=creat();
printf("thedataoflinklist:\n");print(head);}Q:computingthemaxinum
andmininumofthedatanode10.5.3insertoperationtolinklist[eg10.8]createafunctioninsert()torealizeinsertinganewnodewhichdataisxaftertotheIstnodewhichispointedbyhead.analysis
:
comonsituationpre-inserted:
after-inserted:
standartconsideration:
alongthepointerareaofthenodetofindtheist
node,finallyinsertnewnodeaftertheistnodebylinklistheadpointerhead
1325NULL44ps
132head5NULLSpecialsituation:1、nulllistpre=inserted:head=NULLafter-inserted:2、i=0pre-inserted:
after-inserted:3、iout-of-range(i>thenumberofnode)
disposingmanner:(1)error(2)inserttothetailhead4NULL4s
132head5NULLhead
4125NULL3structnode*insert(structnode*head,int
i,intx){structnode*s,*p;s=(structnode*)malloc(LEN);s->num=x;if(head==NULL){head=s;s->next=NULL;}/*1、inserttothenulllinklist*/elseif(i==0) /*non-nulllinklist*/ {s->next=head;head=s;}/*2、newnodeasnewheadnodeoflinklist*/else {p=head;/*lookuptheist
node(pointedbyp)*/for(;p!=NULL&&i>1;p=p->next,i--);if(p==NULL) /*3、errorout-of-range*/
printf("Outoftherange,can'tinsert!\n");else /*4、commonsituation:ppointtotheistnode*/ {s->next=p->next;p->next=s;}}return(head);}main(){structnode*head;
inti,x;
printf("inputdatatocreat
linklist(endby<=0):\n");head=creat();
printf("thedataoflinklist:\n");print(head);
printf("insert:i,x=");scanf("%d%d",&i,&x);insert(head,i,x);
printf("thedataoflinklistafterinserted:\n");print(head);}10.5.4thedeleteoperationtolinklist[eg10.8]designafunctiondelete(),todeletethenodewhosedataisxinthelinklist。Commonsituation:Pre-deleted:After-deleted:
q=head;p=q->next;/*lookupthenodewhosevalueisx*/for(;p->num!=x&&p!=NULL;q=p,p=p->next);
if(p!=NULL)/*iffindit,ppointstothex,qpointstotheearlierone*/{q->next=p->next;free(p);}
132head5NULLhead
1325NULL4qpespescial:1、NULLlisthead=NULLerrorinformation2、deletetheheadnodepre-deleted:
after-deleted:3、nosuchnodeerrorinformationhead
4125NULL3head125NULL3structnode*delete_list(structnode*head,intx){structnode*p,*q;if(head==NULL)/*1、blanklist*/
printf("Error!Thelistisempty.\n");elseif(head->num==x)/*2、deletethefirstnode*/head=head->next;else {q=head;p=q->next;for(;p->num!=x&&p!=NULL;q=p,p=p->next); if(p==NULL)/*3、notexist*/
printf("Error!Thenumbeisnotexsist.\n");else{q->next=p->next;free(p);}/*deleteunheadednode*/ }return(head);}10.5.5colligatedexample:menuprogramdesigning/*=======sortedlink_list
operater=======*//*DesignedbySunQiaoping*/#include"stdio.h";#defineNULL0#defineLENsizeof(structnode)structnode{intnum;
structnode*next;};charmenu(void);voidprint(structnode*head);structnode*insert_sortedlist(structnode*head,intx);structnode*creat_sortedlist(void);structnode*delete_list(structnode*head,intx);main(){structnode*head=NULL;
inti,x,flag=1;charch;do{ch=menu();
clrscr();switch(ch){case'1':head=creat_sortedlist();break; case'2':printf("inputanumbertoinsert.x=");
scanf("%d",&x); head=insert_sortedlist(head,x);break; case'3':
printf("inputanumbertodelete.x=");
scanf("%d",&x); head=delete_list(head,x);break; case'4':print(head);break; case'0':flag=0;}}while(flag==1);}/*========menu========*/charmenu(void){charch;
clrscr();
printf("MENU\n");/*puts()*/
printf("==================\n");
printf("1.creat\n");
printf("2.insert\n");
printf("3.delete\n");
printf("4.print\n");
printf("0.exit\n");
printf("==================\n");
printf("Inputyourchoice(0,1,2,3,4):");
ch=getchar();
return(ch);}/*========insert========*/structnode*insert_sortedlist(structnode*head,intx){structnode*s,*p,*q;s=(structnode*)malloc(LEN);s->num=x;if(head==NULL)/*inserttoablanklist*/{head=s;s->next=NULL;}elseif(x<=head->num)/*inserttoheadoflist*/ {s->next=head;head=s;}else {q=head;p=q->next;/*lookuptheplacetoinsert*/ for(;p!=NULL&&x>p->num;q=p,p=p->next); s->next=p;/*insertafterqandaheadofp*/q->next=s; }return(head);}Pre-inserted:After-inserted:head
1368NULL44qs
136head8NULLp/*========creat========*/structnode*creat_sortedlist(void){structnode*head;
intx;
printf("inputdatatocreat
linklist(endby<=0):\n");head=NULL;while(1){scanf("%d",&x);if(x<=0)break;
head=insert_sortedlist(head,x);}return(head);}10.6introductiontounionandenum10.6.1union
1.conception
severalvariablesofdifferenttypeoccupythesamesegmentofstorage.
2.Definitionofunion
commonsituation:unionu_name {memberlist };
eg.uniondata {inti; charch; floatf; };
Sameasdefinitionofstructuretype
3.DefinitionofSharingvariables(1)indirectdefinition
eg:uniondataun1,un2,un3;
(2)directdefiniton──definitevariableswhendefinitingtype
eg.union[data]{inti;charch;floatf;}un1,un2,un3;4.Thestoragelengthoccupiedbysharingvariables:thelengthoflongestmember5.Citingtosharingvariables──citingonebyone例如:un1.i、un1.ch、un1.f5.characteristic
(1)Systemusestheoverlayingtechonologytorealizememorysharingofthesharingvariables’members,soanytimethereisonlyonemembervaluetostoreandbetake.eg,ifun1.i=1,un1.ch=‘c’,un1.f=3.14,
un1.fisthevalidmember.(2)TheaddressofSharingvariableisthesameasthatofeverymember.eg
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年專有技術(shù)開發(fā)合同(三篇)
- 2025年度暖氣片研發(fā)成果轉(zhuǎn)化與應(yīng)用推廣合同
- 建筑工程施工合同范本2024
- 2025年豬肉供應(yīng)鏈管理服務(wù)合同
- 2025年專利申請委托合同樣本(2篇)
- 2025年度事業(yè)單位合同工勞動爭議解決機制合同2篇
- 理財賬戶監(jiān)管合同協(xié)議書
- 國際買賣合同
- 2025年度婚紗影樓婚紗攝影化妝造型師服務(wù)合同3篇
- 私人買賣房屋合同范本4
- 2025年生產(chǎn)主管年度工作計劃
- 2025年急診科護理工作計劃
- 高中家長會 高二寒假線上家長會課件
- 2024-2025學年山東省聊城市高一上學期期末數(shù)學教學質(zhì)量檢測試題(附解析)
- 違規(guī)行為與處罰管理制度
- 個人教師述職報告錦集10篇
- 四川省等八省2025年普通高中學業(yè)水平選擇性考試適應(yīng)性演練歷史試題(含答案)
- 《內(nèi)部培訓師培訓》課件
- 《雷達原理》課件-3.3.3教學課件:相控陣雷達
- 西方史學史課件3教學
- 2024年中國醫(yī)藥研發(fā)藍皮書
評論
0/150
提交評論