290 likes | 300 Views
Understand the concept of pointers, their relationship with arrays, usage with strings, arrays of pointers, and writing improved programs. Learn from Dr. Zhao Qinpei.
E N D
Beginning C Lecture 7 Lecturer: Dr. Zhao Qinpei Email: qinpeizhao@tongji.edu.cn http://sse.tongji.edu.cn/zhaoqinpei/Courses/
Pointers • What a pointer is and how it’s used? • What the relationship between pointers and array is? • How to use pointers with strings? • How you can declare and use arrays of pointers? • How to write an improved calculator program? Beiginning C / Qinpei Zhao
What is a Pointer? Variables that can store addresses are called pointers. a pointer P that contains the address of another variable, called number, which is an integer variable containing the value 5 Beiginning C / Qinpei Zhao
About Pointer • Every pointer will be associated with a specific variable type, and it can be used only to pointer to variables of that type. • int number; • int *p = &number; • The type name void means absence of any type. • NULL is a constant that’s defined in the STL (= 0 for a pointer), is guaranteed not to point to any location in memory. (<stddef.h>, <stdlib.h>, <stdio.h>, <string.h>, <time.h> etc.) Beginning C / Qinpei Zhao
Pointer • Declaring pointers • int *pointer; //create the pointer but doesn’t initialize it. • int *pointer = NULL; //uninitialized pointers are particularly dangerous. • int *pointer = & number; //initialize with the address of a variable that you’ve already declared. • double value, *pVal, fnum; • int *p, q; //only p is a pointer. • Accessing a value through a pointer (* indirection operator 间接运算符) Beginning C / Qinpei Zhao
Using pointers • in arithmetic statements *pointer += 25; • change the variable that pointer points to by pointer = &another_number; Beginning C / Qinpei Zhao
Using a pointer with scanf() • pointers and variables can work together Beginning C / Qinpei Zhao
Testing for a NULL pointer If you want to test the pointer is empty int *pvalue = NULL; int *pvalue = 0; if(pvalue == NULL) { …… } if(!pvalue) { …… } Beginning C / Qinpei Zhao
Pointers to constants • use the constkeyword when you declare a pointer to indicate that the value pointed to must not be changed. • int value = 999; • constint *pvalue = &value; • *pvalue = 888; // error– attempt to change const location. • value = 777; // free to do what you want with value. • the pointer itself is not constant, you can change what it points to. Change only address, not value! • int number = 888; • pvalue = &number; // ok – changing the address in pvalue. Beginning C / Qinpei Zhao
Constant pointers • ensure that the address stored in a pointer cannot be changed • int count = 43; • int *constpcount = &count; //declares and initialize pcountand indicates that the address stored must not be changed. • int item = 34; • pcount = &item; // error– attempt to change a constant pointer • you can still change the value that pcountpoints to • *pcount = 345; // ok- changes the value of count Beginning C / Qinpei Zhao
Arrays and pointers • Anarrayisacollectionofobjectsofthesametypethatyoucanrefertousingasinglename. • e.g.,anarraycalledscores[50]couldcontainbasketballscoresfora50-gameseason.scores[0]isthefirstscoreandscores[49]isthelast.IfyoustartplayinJan.,thethirdgameinJunecanbeamulti-dimensionalarrayreferencedbyscores[5][2]. • Apointerisavariablethathastheaddressofanothervariableorconstantofagiventype. • Apointercanaccessdifferentvariablesatdifferenttimes,aslongasthey havethesametype. Beginning C / Qinpei Zhao
Arrays and pointers • arrays and pointers are really very closely related and they can sometimes be used interchangeably. • Inputasinglecharacterwithscanf() • Readastring * Don’t usethe&operatorandusethearraynamejustlikeapointer(thefirstelementinthearray). What’sthedifference? However,arraysareNOTpointers! Beginning C / Qinpei Zhao
Arrays and pointers Expression&multiple[0]producesthesamevalueastheexpressionmultiple. Ifphasthesamevalueas&multiple[0],howaboutp+1? Beginning C / Qinpei Zhao
Arrays and pointers Anarraynameisjustafixedaddressandisnotapointer. Beginning C / Qinpei Zhao
MultidimensionalArrays • board • board[0] • &board[0][0] Allhavethesamevalue,buttheyaren’tthesamething. Beginning C / Qinpei Zhao
MultidimensionalArrays Referencinganarray,itssubarrays,anditselements. Beginning C / Qinpei Zhao
MultidimensionalArraysandpointers Beginning C / Qinpei Zhao
Accessingarrayelements Beginning C / Qinpei Zhao
Usingmemoryasyougo • Supposeyoudon’tknowthesizeofthearrayinadvance,dynamicmemoryallocationallowsyoutodealwiththat. • Heap:explicitlyallocatememoryatruntimeinaprogram,spaceisreservedinamemoryarea. • Stack:storefunctionsandlocalvariablesinafunction Beginning C / Qinpei Zhao
Dynamicmemoryallocation:malloc() • Thesimpleststandardlibraryfunctionthatallocatesmemoryatruntimeiscalledmalloc(). • Includethe<stdlib.h>headerfile. • Specifythenumberofbytesofmemoryastheargument • Returns theaddressofthefirstbyteofmemoryallocated,apointerisusefultoputtheaddressreturned. Beginning C / Qinpei Zhao
Dynamicmemoryallocation:malloc() • It‘salwaysagoodideatocheckanydynamicmemoryrequestimmediatelyusinganifstatement. • Usingthesizeofoperatorinmemoryallocation.Store75datatimesoftypeint. UsingsizeofinthiswaymeansthatyouautomaticallyaccommodatethepotentialvariabilityofthespacerequiredforavalueoftypeintbetweenoneCimplementationandanother. Beginning C / Qinpei Zhao
Dynamicmemoryallocation:calloc() • Thecalloc()functionprovidesacoupleofadvantagesoverthemalloc()function. • Itallocatesmemoryasanarrayofelementsofagivensize. • Itinitializesthememorythatisallocatedsothatallbitsarezero. • Includethe<stdlib.h>headerfile. • Specifytwoarguments:thenumberofelementsinthearrayandthesizeofthearrayelement(insize_t) • Similartousemalloc(),butthebigplusisthatyouknowthememoryareawillbeinitializedtozero. Beginning C / Qinpei Zhao
Releasingdynamicallyallocatedmemory • Alwaysreleasethememorywhenitisnolongerrequiredwhenyouallocatememorydynamically. • Memoryleak:occurswhenyouallocatethememorydynamicallyandyoudonotretainthereferencetoit,soyouareunabletoreleasethememory.(withinaloop) • void GetMemory(char **p, intnum) • { • *p = (char *)malloc(num); • } • void Test(void) • { • char *str = NULL; • GetMemory(&str, 100); • strcpy(str, "hello"); • printf(str); • } Beginning C / Qinpei Zhao
Basic guidelines • Avoid allocating lots of small amounts of memory. Allocating many small blocks of memory will carry much more overhead than allocating fewer larger blocks. • Only hang on to the memory as long as you need it. • Always ensure that you release the memory that you have allocated. • You need to be especially careful when allocating memory within a loop. Beginning C / Qinpei Zhao
Handlingstringsusingpointers • Useavariableoftype“pointertochar”toreferenceastring. • Stringinputwithmorecontrol • getchar()in<stdio.h>providesamuchmoreprimitiveoperations. • Readonlyasinglecharacteratatime • Butitenablestocontrolwhenstoppingreadingcharacters • Besurethatyoudon’texceedthememoryyouhaveallocatedtostorethe input. • getchar()readsasinglecharacterfromthekeyboardandreturnsitastypeint. Beginning C / Qinpei Zhao
Handlingstringsusingpointers • Readastringterminatedby‘\n’intoanarray • Aslongasthecharacterthatwasstoredisn’t‘\n’,theloopwillcontinue. • Aftertheloopends,the‘\0’characterisaddedinthenextavailableposition. Beginning C / Qinpei Zhao
Arraysofpointers • Createanarrayofpointerstostorethelocationsofthethreestrings: • Thearraydimensioncanonlybespecifiedbyconstantexpressions. • Aftertheloopends,the‘\0’characterisaddedinthenextavailableposition. Beginning C / Qinpei Zhao
Calculatoragain Designing a program • Allowtheuseofsigneddecimalnumbers,includingadecimalpointwithanoptionalleadingsign, -or+,aswellassignedintegers. • Permitexpressionstocombinemultipleoperationssuchas2.5+3.7-6/6. • Addthe^operator,whichwillberaisedtopower,so2^3willproduce8. • Allowalinetooperateonthepreviousresult.Ifthepreviousresultis2.5,thenwriting=*2+7=12. lec7_problem.c Beginning C / Qinpei Zhao
Summary • Strings present a different, and perhaps more difficult problem than numeric data types. • Arrays and pointers can be both used to handle strings. Beginning C / Qinpei Zhao