PROGRAMMING USING C
PROGRAMMING USING C CGS 3460
Popular in Course
Popular in Computer General Studies
This 95 page Class Notes was uploaded by Dr. Fermin Kilback on Friday September 18, 2015. The Class Notes belongs to CGS 3460 at University of Florida taught by Staff in Fall. Since its upload, it has received 16 views. For similar materials see /class/206546/cgs-3460-university-of-florida in Computer General Studies at University of Florida.
Reviews for PROGRAMMING USING C
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 09/18/15
Dynamically Allocated Memow String CGS 3460 Lecture 33 Apr 3 2006 Henl Yang Previously I Dynamic Memory Allocation l Dynamic Allocated Arrays Agenda I Dynamic Allocated Arrays I Dynamic Allocated Strings I Deallocation I Strings Malloc an Array int a a mallocn sizeofint I Can wejust say a mallocn 4 Not a good idea I After malloc you have all the space needed for the array allocated I After that you can use ai or ai to access the elements Calloc an Array int a A callocn sizeofint I Why do we use calloc All elements are initialized to 0 at the time of allocation Realloc an Array int a a mallocn sizeofint a realloca m sizeofint I Why do we use realloc So we can change its size after we malloc or calloc I If rst argument is null realloc malloc I If second argument is zero the memory is freed Strings In C strings are equivalent to a collection array of characters I How do we setup a string 1 char quarterback Palmer 11 7 bytes are allocate for variable name 1 What if Mannings replaced Palmer as QB 1 char director9 El Let s say a guy named Roethlisberger comes along El char quarterback quarterback char malloc 15 How do we use malloc with strings I char tempbuffer char malloc20 I char name I char title I scanf s tempbuffer I name char malIocstrlentempbuffer I strcpyname tempbuffer I strcpytempbuffer D j I 3D k r Jll X 20 I scanf s tempbuffer I title char malIocstrlentempbuffer I strcpytitle tempbuffer Array of strings I If there are multiple strings we can use a 2 dimensional array to store it I But it waste too much space instead we store an array of pointers to strings I char strings NUMBEROFSTRINGS I strings0 strings1 Recycle I Memory leak I Free p malloc freep I Callin free to a memory location not previously alloca ed dynamically eg an element of array a variable can have unpredictable effect I Dangling pointer refer to the pointer pointing to an address that is already freed I Some programmers putp null whenever they free the memory p points to Strings I String an array of characters I String constant String literals I String variable Summary I Dynamic Allocated Arrays I Dynamic Allocated Strings I Deallocation I Strings Before you go I Nothing for today I Enjoy your plan for tonight Pointer and Dynamic Allocated Memory CGS 3460 Lecture 31 Mar 29 2006 HenI Yang Announcement I Corrupted Tar file will result in 5point penalty starting from Homework 5 I Logistics of Homework 4 5 I Restructure of the homework description webpages 1 Don ts How to protect yourself I Post your code online or to the forum email list I Show your code to other students during discussion I Leaves printout of your code on the table I Remain login into your computer when you are away and your roommates or friends can simply walk in and peek I Trying to help out your friends who had a tough time by sharing your code and heshe promised nobody will ever find out 1 Dos I Group discussion about the strategy to solve the problem eg Step 1 calculate adjacent matrix Step 2 go into infinite loop and receive players input I giscussion about how to use certain features of I Ask TA myself tutoring center I Send questions to mailiing lists I Check Textbook I Look at sample code or hints I Discuss with classmates in library E309 etc Discuss over the phone Homework 5 I Webgage I You ll be given test cases for homework 4 I Sample code from homework 4 will not be available until midApril I The grading criteria for correctnessothers is changed to 50 each for this homework I A maximum of 110 points for taking the road less traveled Previously I Use of Pointers I Array and Pointers Agenda I Arrays and Pointers I Dynamic Memory Allocation I Dynamic Allocated Arrays I Deallocation How do these pointers work I p p l p l p p l p p Array and Pointer III int a10 01010101 int p int sum for p ampa0 p lt ampa9 p sum p for p a p lt a 9 P sum p l Array and Pointer IV I Declaration int a10 is not equal to int a l ifp a can we use p2 to point to the third element in array a f Multidimensional Array and p Pointers I I Pointers can point to multidimensional arrays too I Row major Eg char A33 AWHW AWN Am AWHQ AHHW AHHH AHH AHHQ ARHW ARM Ap Ap f Multidimensional Array and p Pointers II Char p p ampA O 0 How do we get to A01 p 1 How do we get to A10 p 3 How do we get to NWM Nmm NWM NWW A23 p 7 or NHM NHW NHM NHW p ampA2 3 NEW NEW N m NEW Multidimensional Array and Pointers III int a1010 01010101 int p for row 0 row lt 10 row for column 0 column lt 10 colu arowcolumn 0 for p ampa00 p lt ampa9 p0 pgt Multidimensional Array and Pointers IV I Remember if I int a10 I Then automatically pointer a points to aO I a is equivalent to ampa0 I What about I int b1010 I Is there an automatic pointer b I Yes but b ampb0 not ampb00 I b is of type int Pointer of pointers x E Summary I Arrays and Pointers Before you go I Read Chapter 17 I Exercise Have a look at 174 I Quiz 4 on March 31 Friday at the beginning of the class I Quiz 4 covers chapter 7 9 homework 4 slides up to Lecture 26 I Homework 4 submission on March 31 Friday at 1159 pm I No late submission for homework 4 struct typedef union enum CGS 3460 Lecture 35 Apr 7 2006 HenI Yang UT Previously I Strings Agenda I Sample Code I Struct I Typedef I Union I Enum 1 Result of Quiz 4 I Average 601 I Max 93 Min 6 I 716 get 90 or more Grading Scale HwQuiz 4 gt70 100 of the grade for homework 50 69 90 of the grade for homework 40 49 80 of the grade for homework 30 39 60 of the grade for the homework 39 or below at most 60 of the grade for the homework 7 Ll By Popular Demand I Sample Code I Sample Code for Strings Struct Union Enum I Structure A collection of values members I Union similar to structure except members share the same storage I Enumerations an integer type whose values are named by the programmers Structure variable I Compared to Array Array all elements have the same type we specify the subscript to pick the element we want 39 Structure elements members can be of different types each member has a name Struct example struct int itemno char name8 float price float discount float tax iteml item2 Struct Initialization struct int itemno char name8 float price float discount float tax iteml 101 gum 100 025 007 item2 103 pizza 500 000 007 l the expression used for initialization has to be constants and string literals Operation on struct printf The price of s is fn itemlname itemlprice printf The price of s has gone up by l dollarn itemlprice 100 printf The new price of s is fn itemlname itemlprice 1 Operation on struct II I We can use scanf to fill in the value of member too I We can use for assignment item2 iteml remember array cannot allocate memory copy the values of the members one by one I only works for structures of compatible types of the same type more about this later I and and other operators do not work on structures struct type I declare struct at each different location when needed bloat the program changing the program later becomes difficult the declarations may not be consistent they are not compatible even if they look exactly the same Structure tag struct item int itemno char name8 float price float discount float tax struct item iteml 101 gum struct item item2 item2 100 025 007 iteml Define a new type with struct typedef struct int itemno char name8 float price float discount float tax Item Use pointer on struct typedef struct int itemno char name8 float price float discount float tax Item Item grocery 101 gum 100 025 007 Item p p ampgrocery l UPS store analogy save the effort of making a copy 1 Nested Array and Struct I Arrays may have structures as their elements i Item grocery10 where Item is a newly defined type struct item inventory100 Inventory3price 495 I Structures may contain arrays and structures as members 39 temname in the previous example I Initializing an array of structures Const struct dialingcode countrycodes Argentina 54 Bangladesh 880 United State 1 1 Summary I Sample Code I Struct I Typedef Before you go I Read Chapter 16 I Exercise 162 163 1610 1611 I You should practice on as many exercises as you can from this chapter I Homework 5 submission on April 11 Tuesday at 1159 pm Debugging CGS 3460 Lecture 27 Mar 20 2006 HenI Yang Previously I Recursive Functions I Function Miscellaneous Information I Program Organization Agenda I Debug Black Box I Writing Program as a black box Expected Test cases Objectives I You want to know if your program generate correct result I You want to find where the program execution sequence has been I You want to find the values of variables of interest at certain point in time Debugging Process Debug Info from compiler You have to understand how the program works and what to expect at each exact point of execution I You have to identify segments Setup what s called critical break points I You have to print out markers and values and make comparisons to what you expected Tips I Put printout of value after the value changed or both before and after I Put printout of value before execution sequence may be altered 1 Tips 2 I Make sure your debugging code can be switch onoff easily I Print something more meaningful not just ABC or whole bunch of value I For critical info you might want to use ifelse to print more meaningful messages even use assert and exit Sample Code 1 Miscellaneous I Grades for Quiz 3 I The understanding of material covered in Quiz 3 is a concern I Problem with tar file and submission I More place you can get help Tutoring Center 2nd floor on CSE building the door on your left when facing the elevator once you open the door immediately turn left and open another door What s ahead I Pointers For the next 2 weeks I What is a pointer I Memory address I What do we do with pointers UT Summary I Debug Before you go I Read Chapter 10 I Exercise 102 I Start working on Homework 4 It will take a much longer time than previous ones Linked List CGS 3460 Lecture 36 Apr 10 2006 HenI Yang UT Previously I Struct Agenda l Briefly introduce union and enum I Linked List Quiz 5 I April 14 Friday beginning of the class I Material Everything pointer Homework 5 you should know about both option 1 and 2 Lectures 28 33 Textbook Chapter 11 12 134 171 174 Exercises assigned Structure tag struct item int itemno char name8 float price float discount float tax struct item iteml 101 gum struct item item2 item2 100 025 007 iteml 1 Nested Array and Struct I Arrays may have structures as their elements i Item grocery10 where Item is a newly defined type struct item inventory100 Inventory3price 495 I Structures may contain arrays and structures as members 39 temname in the previous example I Initializing an array of structures Const struct dialingcode countrycodes Argentina 54 Bangladesh 880 United State 1 1 Union I Looks very similar to struct I The members occupy the same memory space memory allocation not enough for all members but only fits the largest element in the union I Only one member is valid at a time I When to use it For instance a online bank website switch from log in using account number to user selected id Union II union long int accountno char username12 login struct Enumeration Use meaningful words to represent integers intseason Season 1 define SEASON int define SPRING 1 define SUMMER 2 define AUTUMN 3 define WINTER 4 enum season SPRING SUMMER AUTUMN WINTER The enum names and the integer can be interchanged enum integer value starts from 1 Can be used for declaration eg enum season s1 Can be used for typedef as well 1 Linked List I Dynamic memory allocation is useful in building lists trees graphs and other data structures I Data structure and algorithm would be an interesting course to take for those of you who are major in CIS or EE I Our discussion is limited to linked list Linked List I What is a list Node Link I An alternative to Array I ProsCons More flexible Can grow and shrink as necessary quot Insert and delete node with particular index Cannot be randomly accessed sorted ordered list quot nonuniformed find time Linked List I Operations gsm a a Create a node a Insert a Search a Query a Print Build a Linked List I l Build a structure representing a node struct athlete float speed struct athlete next I Initialize the node struct athelete first NULL 1 Build a linked list Create a node I allocate memory for the node I storing data into the node I insert the node into the list struct athlete newplayer newplayer mallocsizeofstruct athelete newplayerspeed 990 newplayer9next NULL first newplayer Summary I Briefly introduce union and enum I Linked List Before you go I Read Section 175 177 I Exercise how to delete nodes and print all nodes in a linked list I Homework 5 submission on tomorrow at 1159 pm late submission on April 13 Thursday at 1159 pm Macros and Preprocessor CGS 3460 Lecture 39 Apr 17 2006 HenI Yang Previously I Operations on Linked list Create and Insert Agenda l Linked List More insert lookup and delete I Preprocessor Linked List I Operations gsm a a Create a node a Insert a Search a Query a Print Build a Linked List I l Build a structure representing a node struct athlete float speed struct athlete next I Initialize the node struct athelete first NULL 1 Build a linked list Create a node I allocate memory for the node I storing data into the node I insert the node into the list struct athlete newplayer newplayer mallocsizeofstruct athelete newplayerspeed 990 newplayer9next NULL first newplayer Insert a node insert in the front newplayer mallocsizeofstruct athelete newplayer9speed 9 85 newplayer9next first next first newplayer Insert a node insert at the end newplayer mallocsizeofstruct athelete newplayer9speed 10 10 newplayer9next NULL first next9next newplayer Search and Delete I Search for p first p NULL p p next I Delete almost reverse of insertion locating the node to be deleted see search a linked list altering the previous node to bypass the deleted node calling free to reclaim the space occupied by the deleted node I What to do to print everything out exercise Insert a node insert in between newplayer mallocsizeofstruct athelete newplayer speed 10 00 newplayer next NULL struct athelete q for p first p NULL p p9next if p speed gt 1000 newplayer next q next q next newplayer break q P Pointer to Functions Pass as an argument in other function Exception handling More flexible and abstract programming int f int quot a function declaration not definition Example ivoid qsort void base sizet nmemb sizet size int compare const void const void Preprocessors Directives include define are handled by preprocessor Preprocessing is handled prior to compilation C prograr is rlodified C prog we Object Code Powerful but can be hard to debug l Recommended to be used carefully and moderately Preprocessor Directives I Macro definition quotde neundef I File inclusion include I Conditional Compilation 7 if ifdef ifndef elseif else I Others 7 error line pragma More about Directives I Directives always begin with I Directives can appear anywhere in the program I Comments can be on the same line as a directive I No need for I No need for I Customary use upper case as constant name Why use Macro I Primary Reasons Z It makes programs easier to read It makes programs easier to modify Z It helps avoid inconsistencies and typographical errors I Other Reasons Z Making minor changes to the syntax of C eg BEGIN END instead of Renaming Types define BOOL int Controlling conditional compilation define DEGUB empty replacement is ok Parameterized Macros define identifier x1 x2 xn replacementlist I define MAXX y XgtyXIy I define ISEVENn n2 O I define getchar getcstdin 1 Compare Parameterized Macros to Func ons Usually for simple functions The program may be slightly faster no preparation and runtime overhead Generic and not restricted to the types of the functions shorthand compiled code will usually be larger each invocation result in one copy arguments not type checked cannot use pointers to a macro may evaluate its arguments more than once n MAXi j n igtyi1y hard to debug try avoid anything that comes with side effects 1 Rules for Macros I A macro s replacement list may contain other macros I Preprocessor replaces only entire tokens not portions of tokens I macro definition normally remains in effect until the end of the file in which it appears that is scope does not apply I macro may not be defined twice unless the definition is identical to the old one I macros may be undefined by undef directive