1PointersCS217Pointers• Variableswhosevaluesaretheaddresses ofvariables• Operations“addressof”(reference) &“indirection”(dereference) *arithmetic +,-• Declarationmimicsusechar*p;*pisachar,so pisapointertoacharPointers(cont)• Supposex andy areintegersandp isapointertoaninteger…int x,yint *p;p=&x; p getstheaddressofxy=*p; y getsthevaluepointedtobypy=*(&x); sameasy=x55xpy2Pointers(cont)• Pointers(e.g.,*p)arevariablesint x,y;int *px,*py;px =&x;pxistheaddressof x*px=0;sets xto 0py =px;pyalsopointsto x*py+=1;increments xto 1y=(*px)++;sets yto 1,xto 2PointerArithmetic• Pointerarithmetictakesintoaccountthestride(sizeof)thevaluepointedtochar*p;p+=i;increments pby ielementsp-=i;decrements pby ielementsp++;increments pby 1elementp--;decrements pby 1element• Ifp andq arepointerstosametypep– qnumberofelementsbetween pand q• Otherops:p<q;<===!=>= >p andq mustpointtothesamearraynoruntimecheckstoensurethisPointers&Arrays• Arraynamesareconstantpointersint a[10];int *p;p=a;ppointsto a[0]a++;illegal;can’tchangeaconstantp++;legal; pisavariable• Subscriptingisdefinedintermsofpointersa[i]*(a+i)&a[i]a+ip=&a[0] &*(a+0) &*a a3Pointers&Arrays• Pointerscan“walkalong”arraysint a[10],i,*p,x;p=a;pgets&a[0]x=*p;xgets a[0]p=p+1;ppointsto a[1]y=*p;xgets a[1]p++;ppointsto a[2];Pointers&Strings• Stringconstantsdenoteconstantptrs toactualcharschar*msg=“HELLO”;andcharmsg[]=“HELLO”;char*p=msg;ppointsto1stcharacterof “HELLO”• Stringscanbeusedwheneverarraysofcharsareusedstaticchardigits[]=“0123456789”;putchar(digits[i]);H E L L O 0msgArgumentPassing• Passingpointerstofunctionssimulatespassingarguments“byreference”voidswap(intx,int y){intt;t=x;x=y;y=t;}int a=1,b=2;swap(a,b);printf(“%d%d\n”,a,b);voidswap(int*x,int *y){intt;t=*x;*x=*y;*y=t;}int a=1,b=2;swap(&a,&b);printf(“%d%d\n”,a,b);PassingbyvaluePassingbyreference4Pointer&ArrayParameters• Arrayparameters:formalsarenotconstant;theyarevariablespassinganarraypassesapointerto1stelementarrays(andonlyarrays)arepassed“byreference”voidf(Ta[]){...}isequivalenttovoidf(T*a){...}Example• Copyingstringsvoidscopy(char*s,char*t)copies tto s• Arrayversion• Pointerversionvoidscopy(chars[],chart[]){int i;for(i=0;t[i];i++)s[i]=t[i];}voidscopy(char*s,char*t){while(*t)*s++=*t++;}ArraysofPointers• Usedtobuildtabularstructures• Indirection(*)haslower precedencethan[]char*line[100];sameaschar*(line[100]);declaresarrayofpointerstostrings*line[i]referstothe0thcharacterofthe ith string5ArraysofPointers(cont)• Canbeinitialized• Examplechar*name[]={“January”,“February”,...,“December”};• Anotherexampleint a,b;int *x[]={&a,&b,&b,&a,NULL};ArraysofPointers(cont)• Similartomulti-dimensionalarraysint a[10][10];both a[i][j]int *b[10];b[i][j]arelegalreferencesto ints• Arraya:2-dimensional10x10arraystoragefor100elementsallocatedatcompiletimea[6] isaconstant;a[i] cannotchangeatruntimeeachrowofa has10elements• Arrayb:anarrayof10pointers;eachelementcouldpointtoanarraystoragefor10pointersallocatedatcompiletimevaluesofthesepointersmustbeinitializedatruntimeb[6] isavariable;b[i] canchangeatruntimeeachrowofb canhaveadifferentlength(raggedarray)ArrayofPointers(cont)• Anotherexamplevoidf(int*a[10]);isthesameasvoidf(int**a);andvoidg(inta[][10]);isthesameasvoidg(int(*a)[10]);**a=1;islegalinboth f& g6Command-LineArguments• Byconvention,main iscalledwith2argumentsint main(intargc,char*argv[])argc isthenumberofargumentsargv isanarrayofpointerstothearguments• Example:echohelloworldargc =3argv[0]=“echo”argv[1]=“hello”argv[2]=“world”argv[3]=NULLImplementationofechoint main(intargc,char*argv[]){inti;for(i=1;i< argc;i++)printf(“%s%c”,argv[i],(i< argc-1)?‘‘:‘\n’);return0;}PointerstoFunctions• UsedtoparameterizeotherfunctionsvoidSortStrings(char*v[],intn,int (*compare)(char*,char*)){...if((*compare)(v[i],v[j])<=0){...}...}7PointerstoFunctions(cont)• Declarationsyntaxcanconfuse:int (*compare)(void*,void*)declares comparetobea“pointertoafunctionthattakestwovoid*argumentsandreturnsan int”int *compare(void*,void*)declarescompare
View Full Document