360 likes | 436 Views
C Review Topics. malloc File I/O ( fgets , strtok ) Splitting code into multiple files Passing parameters (by reference) (Crazy pointers). File I/O. That seems like a useful thing to learn. Every* language has a common way of reading in a file: Read line by line into a string
E N D
C Review Topics • malloc • File I/O (fgets, strtok) • Splitting code into multiple files • Passing parameters (by reference) • (Crazy pointers)
File I/O That seems like a useful thing to learn. • Every* language has a common way of reading in a file: • Read line by line into a string • Parse the string • Every* language has multiple ways of reading from a file • read particular types knowing the format • read character by character • read into an array of words • read a certain number of characters at a time I don’t feel like learning something different for every language *Unverified statement. Every language I have encountered.
File I/O in C • Open file • Read one line in at a time into a string (char []) • Process that string FILE *fopen(const char *path, const char *mode); char *fgets(char *s, int size, FILE *stream); fgets does NOT allocate memory Parsing: char *strtok(char *str, const char *delim); Storing for later: void *malloc(size_t size); size_tstrlen(const char *s);
malloc • When do you need to allocate space? • When you don’t know the size of your array beforehand • When you want to allocate space within a function but use the space outside the function • We don’t know the size of the data we will use • When you don’t know how many things you need to allocate space for
malloc • When do you allocate space? • Dynamic size: You don’t know how big you want it / how many you will need until during program • Lifetime: You want to create it inside a function but use it outside a function
mallocexampleRead in test scores, sort, avg, mean 4 steps to programming. Clarification Design Implementation Debugging
Clarification Nail down the inputs and outputs - exact formats Scores are integers The number of scores is the first line of a file Scores are stored in a file Print out the scores in descending order Print out the average Print out the median
Clarification Input file – first line contains number of tests, rest of the lines contain test scores, one score per line. Scores are integers. filename is 2nd command-line arg Print out scores in order Print out average score Print out mean score We don’t know how many test scores
Design // open file // read in number of tests // allocate array containing that many numbers // then, for each test score { // read in the number // store it in the array } // sort the array // print out average // print out median // print out each tests score in order
Implementation int *array; char buffer[100]; intnumtests; // open file FILE *fp = fopen(argv[1],”r”); // read in number of tests fgets(buffer, 100,fp); numtests = atoi(buffer); // allocate array containing that many numbers // then, for each test score { // read in the number // store it in the array } // sort the array // print out average // print out median // print out each tests score in order
Implementation int *array; char buffer[100]; intnumtests, i; // open file FILE *fp = fopen(argv[1],”r”); // read in number of tests fgets(buffer, 100,fp); numtests = atoi(buffer); // allocate array containing that many numbers array = (int *)malloc( sizeof(int)*numtests); // then, for each test score for(i=0;i<numtests;i++) { int score; // read in the number fgets(buffer,100,fp); score = atoi(buffer); // store it in the array array[i] = score; }
One step further • Same idea, but instead of storing the ints into an int array, let’s store the string read in into an array of strings.
Implementation char **array; char buffer[100]; intnumtests, i; // open file FILE *fp = fopen(argv[1],”r”); // read in number of tests fgets(buffer, 100,fp); numtests = atoi(buffer); // allocate array containing that many numbers array = (char **)malloc( sizeof(char *)*numtests); // then, for each test score for(i=0;i<numtests;i++) { // read in the string fgets(buffer,100,fp); // allocate space for string array[i] = (char *)malloc(sizeof(char)*(strlen(buffer)+1); // copy string over strcpy(array[i],buffer); }
Implementation for(i=0;i<numtests;i++) { // read in the string fgets(buffer,100,fp); // allocate space for string array[i] = (char *)malloc(sizeof(char)*(strlen(buffer)+1); // copy string over strcpy(array[i],buffer); }
Pointer Review – what prints out? int x = 3, y = 4; int *pX = &x, *pY = &y; (pX == pY) ? Print(“Same\n”): print(“Not Same\n”); (*pX == *pY) ? Print(“Equal\n”) : print(“NEqual\n”); x = y (pX == pY) ? Print(“Same\n”): print(“Not Same\n”); (*pX == *pY) ? Print(“Equal\n”) : print(“NEqual\n”); x = 10; pX = pY; (pX == pY) ? Print(“Same\n”): print(“Not Same\n”); (*pX == *pY) ? Print(“Equal\n”) : print(“NEqual\n”);
Draw the memory char *c[]={ "ENTER", "NEW", "POINT", "FIRST" }; printf(“%s”,c[2]); printf(“%s “, &(c[0][3]));
Structs • What do you know about structs?
Structs • What do you know about structs? • They can hold different types of data • They can hold multiple pieces of data • You access variables using the ‘.’ notation • It is a user-defined type • If you have a pointer to a struct, you use ‘->’ rather ‘.’
Structs • What do you know about structs? • You can create your own data type • Make many copies of that data type • dynamically allocate structs • Variables with multiple fields – programmer defines what the fields hold
Structs typedefstruct _product { int weight; floatprice; } product; How do I declare three variables, named apple, banana, and melon, of type product? struct _product apple, banana, melon; product apple, banana, melon; apple.weight = 5;
Structs typedefstruct _product { int weight; floatprice; } product; product apple; product banana, melon;
Structs typedefstruct _product { int weight; floatprice; } product; product apple, banana, melon; How do I set the weight field of apple?
Structs typedefstruct _product { int weight; floatprice; } product; product apple, banana, melon; How do I set the weight field of apple? apple.weight = 5;
Linking pointers Typdefstruct _link{ int value; struct _link *next; } link; link l1, l2, l3, l4; link *p1, *p2, *p3, *p4; p1 = &l1; p2 = &l2; p3 = &l3; p4 = &l4; l1.value = 1; l2.value = 2; l3.value = 4; l4.value = 8; p1->next = p2; p2->next = p3; p3->next = p4; p4->next = p1; p1-value = 5; p1->next->value = 3; p1->next->next->value = 7; for(i=0;i<4;i++) { printf(“%d, “,p2->value); p2 = p2->next; } p2 = null; p3 = null; p4 = null;
Splitting code • main code - something.c • helper functions - blahblah.c • header files - blahblah.h • To compile: • gccsomething.cblahblah.c • OR: you can compile separately and combine later • gcc –c something.c • gcc –c blahblah.c • gccblahblah.osomething.o
header files (.h) • What goes into a header file? • type definitions (i.e. structs) • function definitions • global variable declarations (using extern keyword) • A guard to only be read once • What does not go into a header file? • Local variable declarations • Function implementations
stringfunctions.h #ifndefSTRINGFUNCTIONS_H #define STRINGFUNCTIONS_H intcountchars(char c, char *str); intcountwords(char *filename); intstringlength(char *str); #endif
main code • file can be named anything • must contain main • must contain #include “stringfunctions.h” after other #includes • must NOT contain #include “stringfunctions.c”
helper code • In this case, named stringfunctions.c • must contain #include “stringfunctions.h” after other #includes • must contain all implementations of the functions declared in stringfunctions.h • must contain declarations of all global variables declared in stringfunctions.h
Function calls / pointersPass int by value void swap(intx, int y) int temp = x; x = y; y = temp; } int main () { int x=100, y = 50; swap(x, y); printf(“x = %d, y = %d\n”,x,y); return 0; }
Function calls / pointersPass pointer (reference) by value void swap(int*x, int *y) int temp = *x; *x = *y; *y = temp; } int main () { int x=100, y = 50; swap(&x, &y); printf(“x = %d, y = %d\n”,x,y); return 0; }
C++ - Function calls / pointersPass int by reference – Syntax of passing an int, Actions of passing a pointer to int void swap(int& x, int& y) int temp = x; x = y; y = temp; } int main () { int x=100, y = 50; swap(x, y); printf(“x = %d, y = %d\n”,x,y); return 0; }
Draw the memory char *c[]={ "ENTER", "NEW", "POINT", "FIRST" }; printf(“%s”,c[2]); printf(“%s “, &(c[0]3]));
Crazy Pointers char *c[]={ "ENTER", "NEW", "POINT", "FIRST" }; char **cp[]={&(c[3]),&(c[2]),&(c[1]),c}; char ***cpp=&(cp[1]); printf(“%s”,**cpp); printf(“%s “, &((*(cpp[2]))[3])); printf(“%c\n”,cpp[0][1][3]);
Count & Print out all lines in file that contain a particular word (grep) • Print out the count first • Don’t read in the file twice • (You’ll need to malloc stuff)