1 / 36

C Review Topics

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

gisela
Download Presentation

C Review Topics

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. C Review Topics • malloc • File I/O (fgets, strtok) • Splitting code into multiple files • Passing parameters (by reference) • (Crazy pointers)

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

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

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

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

  6. mallocexampleRead in test scores, sort, avg, mean 4 steps to programming. Clarification Design Implementation Debugging

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

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

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

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

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

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

  13. 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); }

  14. 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); }

  15. 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”);

  16. Draw the memory char *c[]={ "ENTER", "NEW", "POINT", "FIRST" }; printf(“%s”,c[2]); printf(“%s “, &(c[0][3]));

  17. Structs • What do you know about structs?

  18. 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 ‘.’

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

  20. 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;

  21. Structs typedefstruct _product { int weight; floatprice; } product; product apple; product banana, melon;

  22. Structs typedefstruct _product { int weight; floatprice; } product; product apple, banana, melon; How do I set the weight field of apple?

  23. Structs typedefstruct _product { int weight; floatprice; } product; product apple, banana, melon; How do I set the weight field of apple? apple.weight = 5;

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

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

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

  27. stringfunctions.h #ifndefSTRINGFUNCTIONS_H #define STRINGFUNCTIONS_H intcountchars(char c, char *str); intcountwords(char *filename); intstringlength(char *str); #endif

  28. main code • file can be named anything • must contain main • must contain #include “stringfunctions.h” after other #includes • must NOT contain #include “stringfunctions.c”

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

  30. 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; }

  31. 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; }

  32. 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; }

  33. Extra if you have time…

  34. Draw the memory char *c[]={ "ENTER", "NEW", "POINT", "FIRST" }; printf(“%s”,c[2]); printf(“%s “, &(c[0]3]));

  35. 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]);

  36. 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)

More Related