1 / 29

Beginning C

Understand the concept of pointers, their relationship with arrays, usage with strings, arrays of pointers, and writing improved programs. Learn from Dr. Zhao Qinpei.

lpruitt
Download Presentation

Beginning C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Beginning C Lecture 7 Lecturer: Dr. Zhao Qinpei Email: qinpeizhao@tongji.edu.cn http://sse.tongji.edu.cn/zhaoqinpei/Courses/

  2. 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

  3. 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

  4. 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

  5. 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

  6. Using pointers • in arithmetic statements *pointer += 25; • change the variable that pointer points to by pointer = &another_number; Beginning C / Qinpei Zhao

  7. Using a pointer with scanf() • pointers and variables can work together Beginning C / Qinpei Zhao

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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

  13. Arrays and pointers Expression&multiple[0]producesthesamevalueastheexpressionmultiple. Ifphasthesamevalueas&multiple[0],howaboutp+1? Beginning C / Qinpei Zhao

  14. Arrays and pointers Anarraynameisjustafixedaddressandisnotapointer. Beginning C / Qinpei Zhao

  15. MultidimensionalArrays • board • board[0] • &board[0][0] Allhavethesamevalue,buttheyaren’tthesamething. Beginning C / Qinpei Zhao

  16. MultidimensionalArrays Referencinganarray,itssubarrays,anditselements. Beginning C / Qinpei Zhao

  17. MultidimensionalArraysandpointers Beginning C / Qinpei Zhao

  18. Accessingarrayelements Beginning C / Qinpei Zhao

  19. Usingmemoryasyougo • Supposeyoudon’tknowthesizeofthearrayinadvance,dynamicmemoryallocationallowsyoutodealwiththat. • Heap:explicitlyallocatememoryatruntimeinaprogram,spaceisreservedinamemoryarea. • Stack:storefunctionsandlocalvariablesinafunction Beginning C / Qinpei Zhao

  20. Dynamicmemoryallocation:malloc() • Thesimpleststandardlibraryfunctionthatallocatesmemoryatruntimeiscalledmalloc(). • Includethe<stdlib.h>headerfile. • Specifythenumberofbytesofmemoryastheargument • Returns theaddressofthefirstbyteofmemoryallocated,apointerisusefultoputtheaddressreturned. Beginning C / Qinpei Zhao

  21. Dynamicmemoryallocation:malloc() • It‘salwaysagoodideatocheckanydynamicmemoryrequestimmediatelyusinganifstatement. • Usingthesizeofoperatorinmemoryallocation.Store75datatimesoftypeint. UsingsizeofinthiswaymeansthatyouautomaticallyaccommodatethepotentialvariabilityofthespacerequiredforavalueoftypeintbetweenoneCimplementationandanother. Beginning C / Qinpei Zhao

  22. Dynamicmemoryallocation:calloc() • Thecalloc()functionprovidesacoupleofadvantagesoverthemalloc()function. • Itallocatesmemoryasanarrayofelementsofagivensize. • Itinitializesthememorythatisallocatedsothatallbitsarezero. • Includethe<stdlib.h>headerfile. • Specifytwoarguments:thenumberofelementsinthearrayandthesizeofthearrayelement(insize_t) • Similartousemalloc(),butthebigplusisthatyouknowthememoryareawillbeinitializedtozero. Beginning C / Qinpei Zhao

  23. 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

  24. 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

  25. Handlingstringsusingpointers • Useavariableoftype“pointertochar”toreferenceastring. • Stringinputwithmorecontrol • getchar()in<stdio.h>providesamuchmoreprimitiveoperations. • Readonlyasinglecharacteratatime • Butitenablestocontrolwhenstoppingreadingcharacters • Besurethatyoudon’texceedthememoryyouhaveallocatedtostorethe input. • getchar()readsasinglecharacterfromthekeyboardandreturnsitastypeint. Beginning C / Qinpei Zhao

  26. Handlingstringsusingpointers • Readastringterminatedby‘\n’intoanarray • Aslongasthecharacterthatwasstoredisn’t‘\n’,theloopwillcontinue. • Aftertheloopends,the‘\0’characterisaddedinthenextavailableposition. Beginning C / Qinpei Zhao

  27. Arraysofpointers • Createanarrayofpointerstostorethelocationsofthethreestrings: • Thearraydimensioncanonlybespecifiedbyconstantexpressions. • Aftertheloopends,the‘\0’characterisaddedinthenextavailableposition. Beginning C / Qinpei Zhao

  28. 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

  29. 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

More Related