Homework Continuing K&R Chapter 6.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
1 CS 162 Introduction to Computer Science Chapter 8 Pointers Herbert G. Mayer, PSU Status 11/20/2014.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 Homework / Quiz Exam 2 – Solutions Posted – Questions? Continuing K&R Chapter 6 HW6 is on line – due class 22.
1/18 Strukture. 2/ Osnove struktura struct point { int x; int y; }; y x0, 0 (4, 3) struct { … } x, y,
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 Homework HW6 due class 22 K&R 6.6 K&R 5.7 – 5.9 (skipped earlier) Finishing up K&R Chapter 6.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Homework Finishing up K&R Chapter 6 today Also, K&R 5.7 – 5.9 (skipped earlier)
Homework Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Structures CSE 2031 Fall March Basics of Structures (6.1) struct point { int x; int y; }; keyword struct introduces a structure declaration.
D. GotsevaPL-Lectures1 Programming Languages Lectures Assoc. Prof. PhD Daniela Gotseva
Advanced Pointers and Structures Pointers in structures Memory allocation Linked Lists –Stacks and queues Trees –Binary tree example.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
C Structures and Memory Allocation
Chapter 5, Pointers and Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Fundamentals of Characters and Strings
12 C Data Structures.
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Week 7 Part 2 Kyle Dewey.
Computer Science 210 Computer Organization
Arrays in C.
Discussion 6 HW4 and Libraries.
Programming Languages and Paradigms
Homework / Exam Continuing K&R Chapter 6 Exam 2 after next class
Computer Science 210 Computer Organization
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Pointers and Pointer-Based Strings
Chapter 16 Pointers and Arrays
Your questions from last session
Homework Finishing K&R Chapter 5 today Starting K&R Chapter 6 next
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Basic – week 9
Homework Starting K&R Chapter 5 Good tutorial on pointers
Structures CSE 2031 Fall February 2019.
Homework Reading Programming Assignments Finish K&R Chapter 1
Homework Continue with K&R Chapter 5 Skipping sections for now
Data Structures and Algorithms Introduction to Pointers
Data Structures & Algorithms
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
Chapter 9: Pointers and String
Structures CSE 2031 Fall April 2019.
Structures CSE 2031 Fall May 2019.
Characters and Strings Functions
Structures EECS July 2019.
C Structures and Memory Allocation
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

Homework Continuing K&R Chapter 6

Review structs struct point { int x; int y; struct point { }; int x; struct point pt1, pt2; struct point maxpt = {320, 200}; struct point { int x; int y; }pt1,pt2; Initialization

Review structs struct rect { struct point pt1; struct point pt2; };  Note: must have ; following } struct rect box;

Review structs box.pt1.x = 5; box.pt1.y = 10; box.pt2.x = 10; area = (box.pt2.x – box.pt1.x) * (box.pt2.y – box.pt1.y); Assosciativity

What can we do with a struct? Reference members box.pt2.x = box.pt1.x + width; Assign as a unit pt2 = pt1; Create a pointer to it struct point *ppt1; ppt1 = &pt1;

What can we do with a struct? Not legal to compare structs if (pt1 = = pt2) …  INVALID Must be done as: if (pt1.x = = pt2.x && pt1.y = = pt2.y) …

structs and Functions, K&R 6.2 /* ptinrect: if point p in rect r, return 1 else return 0 note: slightly different from K&R example */ int ptinrect (struct point p, struct rect r) { return p.x >= r.pt1.x && p.x <= r.pt2.x && p.y >= r.pt1.y && p.y <= r.pt2.y; }

Arrays of structs, K&R 6.3 Multiple related arrays char * keyword[NKEYS]; int keycount[NKEYS]; Can be implemented as an array of structs struct key { char *word; int count; } keytab [NKEYS]; Array of a struct

Arrays of structs Alternative array of structs implementation struct key { char *word; int count; }; struct key keytab[NKEYS];

Arrays of structs Initialization for an array of structs struct key { char *word; int count; } keytab[ ] = { “auto”, 0, … “while”, 0 }; Another way to write keytab[ ] = { {“auto”, 0}, … {“while”, 0} }; The address of the strings save in char * word You can type char * test = “I am Ramin”; and it has just 4 Bytes

sizeof structs sizeof is a compile-time unary operator Can be used to get the number of integer bytes (actually size_t): sizeof object sizeof (type name) NKEYS can be dynamically derived using sizeof #define NKEYS (sizeof keytab / sizeof (struct key)) #define NKEYS (sizeof keytab / sizeof keytab[0])

Pointers to structs, K&R 6.4 Declare and initialize a pointer to struct struct point p; struct point *pp = &p; Refer to members of struct p via pointer pp (*pp).x and (*pp).y  See precedence More commonly done as: pp->x and pp->y  See precedence

Pointers to structs struct string { int len; char *cp; } *p; struct string xp; p = &xp; Expression Same as Value / Effect ++p->len ++(p->len) increments len *p->cp *(p->cp) value is a char *p->cp++ *((p->cp)++) value is a char increments cp

Example of pointers to struct struct string a = {8 , “yellow”}; struct string b = {9 , “black”}; struct string * ptr_a = &a; p = &b; ptr_a->len = ? ptr_a->cp = ? p->len = ? p->cp = ? 8 pointer to address of ‘y’ and *ptr_a->cp = ‘y’

Pointers to structs /* ptinrect: (pointer version) if point p in rect r, return 1 else return 0 */ int ptinrect (struct point *pp, struct rect *rp) { return pp->x >= rp->pt1.x && pp->x <= rp->pt2.x && pp->y >= rp->pt1.y && pp->y <= rp->pt2.y; }

Self Referential structs, K&R 6.5 Count the occurrences of all the words in some input Look at this binary tree structure (Pg. 139) for the sentence “now is the time for all good men to come to the aid of their party” At any node, the left subtree only has words that are lexicographically less than the word at the node. The right subtree has words that are greater. now is the for all aid come men of time party their to good

Self Referential structs struct tnode { /* the tree node struct */ char *word; /* points to the word at this node */ int count; /* has a count of occurances */ struct tnode *left; /* a word < one at this node */ struct tnode *right; /* a word > one at this node */ }; OK to have a pointer to a struct of same type in its own definition NOT OK to have a struct itself in its own definition (OK to have a different struct as a member)! Don’t need to put a word 2 times in the tree Same structure inside the structure -> how many bytes for memory?!

Tree of struct tnodes tnode *root char *word int count keyword \0 tnode *left tnode *right keyword \0 … char *word int count tnode *left tnode *right … A pointer is always 4 bytes. So it just saves the address and doesn’t matter the length of string Just the address of a node for left and right … … char *word int count tnode *left tnode *right … …

Self Referential structs Each node is a struct tnode with a string value and a count of occurrences Each node also contains a pointer to a left child and a right child Each child is another struct tnode

Declarations / Prototypes #include <stdio.h> #include <ctype.h> (see functions in App. B2, pp. 248-249, K&R) #include <string.h> (see functions in App. B3, pp. 249-250, K&R) #define MAXWORD 100 int getword(char *word, int lim); struct tnode *addtree(struct tnode *, char *); void treeprint(struct tnode *); Getword -> parse the paragraph in to words Addtree -> adds the structure of the word in to a tree structure

Main program int main( ) { struct tnode *root; /* ptr to root for binary tree */ char word[MAXWORD]; /* word to get from stdin */ root = NULL; /* initially, no tnodes in tree */ /* OK that root pointer points to NULL initially */ while (getword(word, MAXWORD) != EOF) /* getword from stdin */ if (isalpha(word[0])) /* from ctype.h library */ root = addtree(root, word); /* expect not NULL anymore */ treeprint(root); /* print it out in order */ return 0; }

getword ( ) /* getword: get next word or character from input */ /* a word is either a string of letters and digits beginning with a letter, or a single non-white space character */ int getword(char *word, int lim) { int c, getch(void); void ungetch(int); char *w = word; while (isspace(c = getch())) /* skip spaces; c first non-space */ ; if (c != EOF) *w++=c; /* c might be EOF here (empty word) */ if(!isalpha(c)) { /* c (identifier) starts with alpha */ *w = '\0'; return c; } /* if not, form word with 1 non-white space char*/ for( ; --lim > 0; w++) if (!isalnum(*w = getch())) { /* identify alpha or digits */ ungetch(*w); break; /* need to go back 1 character if the end is reached*/ } *w = '\0'; return word[0]; Put space to buffer

addtree ( ) struct tnode *talloc(void); /* allocate. return ptr to tnode */ char *strdup(char *); /* allocate space, copy word there */ /* addtree: add a node with w, at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; /*for empty tree, root is NULL */ if (p == NULL) { /* nothing at this node yet */ p = talloc(); /* allocate a new node */ p->word = strdup(w); /* allocate space, copy word there */ p->count = 1; /* count is 1 */ p->left = p->right = NULL; /* this works; see precedence */ } else if ((cond = strcmp(w, p->word)) == 0) /* string.h */ p->count++; /* repeated word, increment count */ else if (cond < 0) /* note cond remembers strcmp above */ p->left = addtree(p->left, w); /* less: go left subtree */ else /* more, go to right subtree */ p->right = addtree(p->right, w); return p; } It a recursive function

addtree( ) Note, that addtree is recursive. If it adds a node, it might need to add root or any left or right child anywhere down the tree We pass struct tnode *p as first argument, and also pass back the same type - always a pointer to the node at the current recursive nesting level Any time a new node is created: root, p->left or p->right in node above will be set for the FIRST time based on return value from addtree

addtree ( ) When main calls addtree, the return sets root value each time even if the root already pointed to tnode Allows for possible addition of a pointer to a node Why do we need to return a struct tnode *p when we have struct tnode *p as an argument? Can't we just set it via argument, return void from addtree, and write (in main)? addtree(root, word); instead of root = addtree(root, word);

addtree ( ) No, root is already a pointer, struct tnode *p, but it is the pointer p itself that must be modified To modify root, we would need to declare addtree with a pointer to p as 1st arg: void addtree(struct tnode **p, char *w); Call it from main recursively by invocation: addtree(&root, word); Then, addtree could set the value for root directly instead of by return value. Same is true of lower levels when adding a left or right child

talloc ( ) How to write talloc to allocate a tnode and return a pointer. struct tnode *talloc(void) { return (struct tnode *) malloc (sizeof(struct tnode)); }

strdup ( ) strdup ( ) creates space for a character string, copies a word into it (up to null terminator) and returns the char pointer char *strdup(char *s) { char * p; p = (char *) malloc (strlen(s)+1); /* +1 for '\0' */ if (p != NULL) /* if malloc didn’t fail */ strcpy(p, s); /* library function in string.h */ return p; } To save the word

treeprint ( ) To print out tree contents in order: void treeprint (struct tnode *p) { if (p != NULL) { treeprint (p->left); printf (%4d %s\n”, p->count, p->word); treeprint (p->right); }

treeprint Recursion Program Flow now is the for all aid come men of time party their to good 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 Hw6 -> you build this tree based on a text I will give you, then you should print out a histogram of the frequency of the words in the text. So you should use the count variable of the nodes. So walk through the tree many times to get all of the counts.

Table Lookup, K&R 6.6 struct for a linked list of names/definitions struct nlist { /* table entry */ struct nlist *next; /* link to next */ char *name; /* word name */ char *defn; /* word definition */ };

Table Lookup / Linked Lists Array of pointers to null terminated linked lists of structs defining table entries array nlist [0] [1] Sometime you want to figure out how many times a word occurs in a text. In Java it maps each word to a number then search that number. nlist=0 means end of the list [2] [3] [4]

Table Lookup / Linked List Hash search- incoming name is converted into a non-negative integer which is used to index into an array of pointers Hash function to select starting array element unsigned int hash (char *s) { for (hashval = 0; *s != ‘\0’; s++) hashval = *s + 31 * hashval; return hashval % HASHSIZE; } In lookup ( ), code for following a linked list: for (ptr = head; ptr != NULL; ptr = ptr->next) Show an example: test The hashing use to minimize the size of the table for the number of occurs. -> sparsely populated table. So then we should use hashing because we have small slot but maybe in same slot we have more than one items. -> with linked list

Lookup Function /* look for s in hashtab */ struct nlist *lookup(char *s) { struct nlist *np; for (np = hashtab[hash(s)]; np !=null; np=np->next) if (strcmp(s, np->name) ==0) return np; return NULL; }