C程序設(shè)計基礎(chǔ) 英文版 課件 Chapter 7 Pointers_第1頁
C程序設(shè)計基礎(chǔ) 英文版 課件 Chapter 7 Pointers_第2頁
C程序設(shè)計基礎(chǔ) 英文版 課件 Chapter 7 Pointers_第3頁
C程序設(shè)計基礎(chǔ) 英文版 課件 Chapter 7 Pointers_第4頁
C程序設(shè)計基礎(chǔ) 英文版 課件 Chapter 7 Pointers_第5頁
已閱讀5頁,還剩65頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

Chapter11PointersFangWangOutlines7.1PointerVariables

7.2TheAddressandIndirectionOperators

7.3PointersasArguments

7.4PointersasReturnValues

7.5UsingPointersforArrays7.7ArrayArguments7.8PointersandMultidimensionalArrays7.9PointerstoFunctions27.1PointerVariables指針變量Inmostmoderncomputers,mainmemoryisdividedintobytes,witheachbytecapableofstoringeightbitsofinformation:Eachbytehasauniqueaddress.37.1PointerVariablesIftherearenbytesinmemory,wecanthinkofaddressesasnumbersthatrangefrom0ton–1:47.1PointerVariablesEachvariableinaprogramoccupiesoneormorebytesofmemory.Theaddressofthefirstbyteissaidtobetheaddressofthevariable.變量占一個或多個字節(jié)存儲空間,以首字節(jié)的地址作為該變量的地址。Inthefollowingfigure,theaddressofthevariablenumberis0xfff3:50xfff30xfff40xfff50xfff6number7.1PointerVariablesAddressescanbestoredinspecialpointervariables.地址用指針變量來存儲Whenwestoretheaddressofavariabletinthepointervariablep,wesaythatp“pointsto”t.如果P存放了t的地址,就叫做P指向tAgraphicalrepresentation:6t7.1PointerVariablesDeclaringPointerVariablesWhenapointervariableisdeclared,itsnamemustbeprecededbyanasterisk:

int*p;pisapointervariablecapableofpointingtoobjectsoftypeint.指針變量的類型實際上是指針可以指向的對象的類型。int*p;//p是整型指針變量inti;P=&i;//p指向i(p存放i的地址)例如,指針變量p是整型,p就只能指向整型變量,意思是,p只能存放整型變量的地址。比如存放i的地址。77.1PointerVariablesDeclaringPointerVariablesCrequiresthateverypointervariablepointonlytoobjectsofaparticulartype: int*p;/*pointsonlytointegers*/ double*q;/*pointsonlytodoubles*/ char*r;/*pointsonlytocharacters*/ inta; doubleb; charc;Pointervariablescanappearindeclarationsalongwithothervariables:

inti,j,a[10],b[20],*p,*q;87.2TheAddressandIndirectionOperators取地址運算符&和間接尋址運算符*(指針運算符)Tofindtheaddressofavariable,weusethe&(address)operator.&:取地址運算符int*p,t;P=&t;Togainaccesstotheobjectthatapointerpointsto,weusethe*

(indirection)operator.

*:指針運算符,間接尋址(訪問)運算符E.g.*p97.2TheAddressandIndirectionOperatorsTheAddressOperator intt,*p; … p=&t;//把i的地址存放到p里面。則p指向tAssigningtheaddressofttothevariablepmakesp

pointtot:10t7.2TheAddressandIndirectionOperatorsTheAddressOperator

intt; int*p=&t;It’salsopossibletoinitializeapointervariableatthetimeit’sdeclared.可以在聲明指針的同時對它初始化117.2TheAddressandIndirectionOperatorsTheIndirectionOperatorOnceapointervariablepointstoanobject,wecanusethe

*

(indirection)operatortoaccesswhat’sstoredintheobject.一旦用指針指向某個變量后,就可以用*操作符來訪問該變量的值。Ifppointstot,wecanprintthevalueoft.比如,p指向i,所以*p就是訪問i的值,我們可以把*p看成i的別名intt=10,*p=&t;

printf("%d\n",*p);127.2TheAddressandIndirectionOperatorsTheIndirectionOperator

Aslongasp

pointstot,*pisanalias(別名)fort.*p

hasthesamevalueast.Changingthevalueof*p

changesthevalueoft.

13t7.2TheAddressandIndirectionOperatorsTheexampleillustratestheequivalenceof*p

andi.

p=&i;

i=1;

printf("%d\n",i);/*prints1*/ printf("%d\n",*p);/*prints1*/ *p=2; printf("%d\n",i);/*prints2*/ printf("%d\n",*p);/*prints2*/14Classassignment39:pointerDeclareaPointerpPointtoavariableiAssignavaluetoiOutput:pand*p(onthefirstline),&iandi(line2)inti;int*p=&i;157.3PointersasArguments16#include<stdio.h>#include<stdlib.h>intmain(){inti=10,*p;p=&i;printf("%d%d\n",p,*p);printf("%d%d\n",&i,i);return0;}17

#include<stdio.h>voidswap(intp1,intp2);

voidswap(intp1,intp2)

{

intt;

t=p1,p1=p2,p2=t;//swapp1

andp2

}

intmain()

{

inta,b;

scanf("%d%d",&a,&b);

if(a>b)swap(a,b);

printf("min=%d,max=%d\n",a,b);

return0;

}18#include<stdio.h>

voidswap(int*p1,int*p2);

voidswap(int*p1,int*p2)

{

intt;

t=*p1,*p1=*p2,*p2=t;//swap*p1

and*p2

}

intmain()

{

inta,b;

scanf("%d%d",&a,&b);

if(a>b)swap(&a,&b);

printf("min=%d,max=%d\n",a,b);

return0;

}PointerAssignmentCallowstheuseoftheassignmentoperatortocopypointersofthesametype.19PointerAssignmentAssumethatthefollowingdeclarationisineffect:

inti,j,*p,*q;Exampleofpointerassignment:p=&i;Anotherexampleofpointerassignment:

q=p;qnowpointstothesameplaceasp:20PointerAssignmentIfpandqbothpointtoi,wecanchangeibyassigninganewvaluetoeither*por*q: *p=1; *q=2;217.3PointerAssignmentBecarefulnottoconfuse

q=p; with

*q=*p;Thefirststatementisapointerassignment,butthesecondisnot.Theexampleonthenextslideshowstheeffectofthesecondstatement.

22PointerAssignment

p=&i; q=&j; i=1; *q=*p;j=i;237.4pointersasreturnvalues247.5UsingPointersforArraysCallowsustoperformarithmetic—additionandsubtraction—on

pointerstoarrayelements.Thisleadstoanalternativewayofprocessingarraysinwhichpointerstaketheplaceofarraysubscripts.TherelationshipbetweenpointersandarraysinCisacloseone.UnderstandingthisrelationshipiscriticalformasteringC.257.5UsingPointersforArrayspointerscanpointtoarrayelements: inta[10],*p; p=&a[0];//p=a;Agraphicalrepresentation:26PointerArithmetic

*p=1;Wecannowaccessa[0]

through

p;forexample,wecanstorethevalue1ina[0]bywritingAnupdatedpicture:271PointerArithmeticIfppointstoanelementofanarraya,theotherelementsofacanbeaccessedbyperformingpointerarithmetic(oraddressarithmetic)onp.Csupportsthree(andonlythree)formsofpointerarithmetic:AddinganintegertoapointerSubtractinganintegerfromapointerSubtractingonepointerfromanother28PointerArithmeticAddinganIntegertoaPointer

p+1p+jAddinganintegerj

toapointerpyieldsapointertotheelementjplacesaftertheonethatppointsto.Moreprecisely,ifppointstothearrayelementa[i],thenp+j

pointstoa[i+j].29130PointerArithmeticMoreprecisely,ifppointstothearrayelementa[i],thenp+j

pointstoa[i+j].Assumethatthefollowingdeclarationsareineffect:

inta[10],*p,*q,i;Exampleofpointeraddition:

p=&a[2];

q=p+3;

p+=6;PointerArithmeticSubtractinganIntegerfromaPointerIfppointstoa[i],thenp-jpointstoa[i-j].Example:

p=&a[8];

q=p-3;

p-=6;

32PointerArithmeticSubtractingOnePointerfromAnotherWhenonepointerissubtractedfromanother,theresultisthedistance(measuredinarrayelements)betweenthepointers.Ifppointstoa[i]andqpointstoa[j],thenp-qisequaltoi-j.Example: p=&a[5]; q=&a[1];

i=p-q;/*iis4*/ i=q-p;/*iis-4*/33PointerArithmeticSubtractingOnePointerfromAnotherOperationsthatcauseundefinedbehavior:Performingarithmeticonapointerthatdoesn’tpointtoanarrayelementSubtractingpointersunlessbothpointtoelementsofthesamearray347.5UsingPointersforArrayPointerarithmeticallowsustovisittheelementsofanarraybyrepeatedlyincrementingapointervariable.Aloopthatsumstheelementsofanarraya: #defineN10 … inta[N],sum,*p; … sum=0; for(p=&a[0];p<=&a[N-1];p++) sum+=*p;357.5UsingPointersforArrayProcessing Attheendofthefirstiteration:

Attheendoftheseconditeration:

Attheendofthethirditeration:367.5UsingPointersforArrayProcessingTheconditionp<&a[N]

inthefor

statementdeservesspecialmention.It’slegaltoapplytheaddressoperatortoa[N],eventhoughthiselementdoesn’texist.Pointerarithmeticmaysaveexecutiontime.However,someCcompilersproducebettercodeforloopsthatrelyonsubscripting.377.3UsinganArrayNameasaPointerPointerarithmeticisonewayinwhicharraysandpointersarerelated.Anotherkeyrelationship:

Thenameofanarraycanbeusedasapointertothefirstelementinthearray.Thisrelationshipsimplifiespointerarithmeticandmakesbotharraysandpointersmoreversatile.387.3UsinganArrayNameasaPointerSupposethataisdeclaredasfollows:

inta[10];Examplesofusingaasapointer: *a=7;/*stores7ina[0]*/ *(a+1)=12;/*stores12ina[1]*/Ingeneral,a+iisthesameas&a[i].Bothrepresentapointertoelementiofa.Also,

*(a+i)

isequivalenttoa[i].Bothrepresentelementiitself.397.3UsinganArrayNameasaPointerThefactthatanarraynamecanserveasapointermakesiteasiertowriteloopsthatstepthroughanarray.Originalloop:

for(p=&a[0];p<&a[N];p++) sum+=*p;Simplifiedversion:

for(p=a;p<a+N;p++) sum+=*p;407.3UsinganArrayNameasaPointerAlthoughanarraynamecanbeusedasapointer,it’snotallowedtoassignanarraynameanewvalue.Attemptingtomakeitpointelsewhereisanerror: while(*a!=0) a++;/***WRONG***/Thisisnogreatloss;wecanalwayscopyaintoapointervariable,thenchangethepointervariable: p=a;/*pisavariable,aisaconstant*/ while(*p!=0) p++;41Program:ReversingaSeriesofNumbers(Revisited)Thereverse.cprogramofChapter8reads10numbers,thenwritesthenumbersinreverseorder.Theoriginalprogramstoresthenumbersinanarray,withsubscriptingusedtoaccesselementsofthearray.reverse3.cisanewversionoftheprograminwhichsubscriptinghasbeenreplacedwithpointerarithmetic.

427.3UsinganArrayNameasaPointer

/*Reversesaseriesofnumbers(pointerversion)*/

#include<stdio.h>

#defineN10

intmain(void){inta[N],*p;

printf("Enter%dnumbers:",N);for(p=a;p<a+N;p++)scanf("%d",p);

printf("Inreverseorder:");for(p=a+N-1;p>=a;p--)printf("%d",*p);printf("\n");

return0;}437.3UsinganArrayNameasaPointerArrayArguments(Revisited)—Whenpassedtoafunction,anarraynameistreatedasapointer.Example: voidf(inta[],intn){

inti;for(i=0;i<n;i++)a[i]=9;

}Acalloff:

f(b,N); Thiscallcausesapointertothefirstelementofb

tobeassignedtoa;thearrayitselfisn’tcopied.447.3ArrayArgumentsAnarrayparametercanbedeclaredasapointerifdesired.fcouldbedefinedasfollows: voidf(int*p,intn) {

inti;for(i=0;i<n;i++)

p[i]=9; }Declaringptobeapointerisequivalenttodeclaringittobeanarray;thecompilertreatsthedeclarationsasthoughtheywereidentical.45UsingaPointerasanArrayNameCallowsustosubscriptapointerasthoughitwereanarrayname: …inti;for(i=0;i<n;i++)p[i]=9; Thecompilertreatsp[i]as*(p+i).p[i]a[i]

46Cstorestwo-dimensionalarraysinrow-majororder.Layoutofanarraywithrrows:

Ifpinitiallypointstotheelementinrow0,column0,wecanvisiteveryelementinthearraybyincrementingprepeatedly.7.9PointersandMultidimensionalArrays012Col0Col1Col2Col3Considertheproblemofinitializingallelementsofthefollowingarraytozero:

inta[3][4];

inti,j; for(i=0;i<3;i++) for(j=0;j<4;j++) a[i][j]=0;Ifweviewaasaone-dimensionalarrayofintegers,asingleloopissufficient: int*p; for(p=&a[0][0];p<a[0]+12;p++) *p=0;7.9PointersandMultidimensionalArraysForanytwo-dimensionalarraya,theexpressiona[i]isapointertothefirstelementinrowi.p=a[0];isthesameasp=&a[0][0];1#include<stdio.h>2intmain()3{4

inta[3][4]={1,2,3,4,5,6,7,8,9,10,11,12},*p;5

for(p=a[0];p<a[0]+12;p++){6printf("%d",*p);7

if((p-a[0])%4==3)printf("\n");8}9

return0;10}Apointervariable

p

canalsobeusedforprocessingtheelements

injustonerow

ofatwo-dimensionalarray.Tovisittheelementsofrowi,we’dinitializep

topointtoelement0inrowiinthearraya:

p=&a[i][0];

orwecouldsimplywrite

p=a[i];Foranytwo-dimensionalarraya,theexpressiona[i]

isapointertothefirstelementinrowi.7.9PointersandMultidimensionalArraysUsingtheNameofaMultidimensionalArrayasaPointer

inta[3][4];

aisnotapointertoa[0][0];instead,it’sapointertoa[0].Ingeneral:a+iPointstoithelementofa(Pointstoith1-Darray).7.9PointersandMultidimensionalArraysaaaaaaaaaWhenusedasapointer,a

hastypeint

(*)[N]

(pointertoanintegerarrayoflengthN).inta[3][4],(*p1)[4];p1=a;

Thecompilertreatsp[i][j]asa[i][j]

1#include<stdio.h>2intmain()3{4

inta[3][4]={1,2,3,4,5,6,7,8,9,10,11,12},i,j;5

int(*p)[4]=a;6

for(i=0;i<3;i++){

7

for(j=0;j<4;j++)

8printf("%d",p[i][j]);9printf("\n");

10}11

return0;12}inta[M][N],*p=&a[0][0];*(a+i)

issameas

a[i]a[i][j]

p[i*M+j]*(p+i*M+j)*(*(a+i)+j)*(a[i]+j)

7.10pointerstothestringCreatingapointerforthestringcharstr[]="CLanguage";charstr[]=“CLanguage”,*p=str;//p

pointstothestring7.10pointerstothestringchar*p="CLanguage";//p

pointstothestringchar*p;p="CLanguage";//p

pointstothestring

7.10pointerstothestringcharstr[]="CLanguage",*p=str;//p

pointstothestringprintf("%s\n",p);//output:CLanguageprintf("%s\n",p+2);//output:Languageprintf("%s\n",&str[7]);//output:agePP+2&str[7]7.10pointerstothestring1#include<stdio.h>2intmain()3{4

charstr[100],*p=str;//p

pointstothearray.5scanf("%s",str);//inputastring

6

while(*p)p++;

7printf("strlen=%d\n",p-str);8

return0;9}7.11PointerstoPointersApointertoapointerisaformofmultipleindirection,orachainofpointers.inta,*p,**q;P=&a;q=&p;apq&a&p7.12PointerstoFunctions

Theparenthesesaround*pindicatethatpisapointertoafunction.

intmax(inta,intb);//

Prototypeformax

intmin(inta,intb);//

Prototypeformin

int(*p)(inta,intb);//

pointertofunctionsp=max;//p

pointstomaxc=p(a,b);//thesameasc=max(a,b);7.10PointerstoFunctions1#include<stdio.h>2intmax(inta,intb)//computeMaximumvalue

3{4

returna>b?a:b;5}6intmin(inta,intb)////computeMinimumvalue

7{8

returna<b?a:b;9}10intmain()11{12

int(*p)(inta,intb);//pointertofunctions

13p=max;//p

pointstomax

14printf("%d",p(3,4));//callmaxthroughp

15p=min;//p

pointstomin

16printf("%d",p(3,4));//callminthroughp

17

return0;18}DynamicStorageAllocationCsupportsdynamicstorageallocation:theabilitytoallocatestorageduringprogramexecution.Usingdynamicstorageallocation,wecandesigndatastructuresthatgrow(andshrink)asneeded.Dynamicstorageallocationisusedmostoftenforstrings,arrays,andstructures.Dynamicstorageallocationisdonebycallingamemoryallocationfunction.DynamicStorageAllocationMemoryAllocationFunctionsThe<stdlib.h>headerdeclaresthreememoryallocationfunctions:

malloc—Allocatesablockofmemorybutdoesn’tinitializeit.

calloc—Allocatesablockofmemoryandclearsit.

realloc—Resizesapreviouslyallocatedblockofmemory.Thesefunctionsreturnavalueoftypevoid

*(a“generic”pointer).DynamicStorageAllocationNullPointersIfamemoryallocati

溫馨提示

  • 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)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論