CS302 Topic: Fields, Jval, and Dllist. Tuesday, August 30, 2005
|
|
- Kellie Chandler
- 6 years ago
- Views:
Transcription
1 CS302 Topic: Fields, Jval, and Dllist Tuesday, August 30, 2005
2 Announcements Remember: 1 st Labs meet this week Attendance required for 1 st lab!! Class ing list set up: cs302-students@cs.utk.edu Test message sent out last Thursday. If you didn t receive it, see TAs after class!!
3 Software Libraries to Learn and Use Purpose: To gain practice in using existing code (i.e., written by someone else) To see examples of how to package useful code for easy re-use More examples of interface vs. implementation To quickly refresh your memories on using important C constructs Tools we ll learn: Fields: for processing textual input Jval: data type that holds any basic C type DLList: for handling doubly-linked lists. Enables you to handle ordered data of any type and size. JRB: for handling red-black trees. Enables you to sort and search in log time.
4 Recall: Interface vs. Implementation interface implementation Objects hide their functions and data User only has to be familiar with the interface of an object, not its implementation
5 Interface vs. Implementation (con t) Key design principle: Make a clear distinction between interface and implementation Advantages: Supports separation of concerns: Clients care about resources exported from servers Servers care about implementation Interface acts as a contract between a module/component and its clients Information Hiding: Show interface (i.e, what ), not implementation (i.e., how ) Allows changing implementation w/o affecting user
6 Example of Common Interface API: Application Programming Interface API: A set of definitions of the ways a piece of software communicates with another A way of achieving abstraction Specifies a set of commonly-used functions Users/Clients/Programmers can take advantage of API by making use of its functionality (i.e., without having to know about its implementation)
7 Example Real-World APIs PC BIOS call interface Microsoft WIN32 API Carbon API for Mac OS Linux Kernel API Google API APIs composing Microsoft s DirectX
8 Back to our class libraries Tools we ll learn: Fields: for processing textual input Jval: data type that holds any basic C type DLList: for handling doubly-linked lists. Enables you to handle ordered data of any type and size. JRB: for handling red-black trees. Enables you to sort and search in log time.
9 Fields library: fields.c, fields.h Makes reading input easier than getchar(), scanf() or gets() Converts line of input to words (or fields) Example: Line in input file: Go Vols Beat Bama! Resulting fields: Go Vols Beat Bama!
10 Here s the Fields Data Structure, in C: Type def + 4 procedures typedef struct inputstruct { char *name; /* File name */ FILE *f; /* File descriptor */ int line; /* Line number */ char text1[maxlen]; /* The line */ char text2[maxlen]; /* Working--contains fields */ int NF; /* Number of fields */ char *fields[maxfields]; /* Pointers to fields */ int file; /* 1 for file, 0 for popen */ *IS; extern IS new_inputstruct(/* FILENAME -- NULL for stdin */); extern IS pipe_inputstruct(/* COMMAND -- NULL for stdin */); extern int get_line(/* IS */); /* returns NF, or -1 on EOF. Does not close the file */ extern void jettison_inputstruct(/* IS */); /* frees the IS and fcloses the file */
11 Fields functions IS new_inputstruct(filename) Takes file name and returns pointer to new IS structure Memory is malloc()-ed here If file can t be opened, returns NULL (use perror() to print out reason for error) int get_line(is) Puts contents of the next line into text1 Breaks line into words NF contains # of words First NF slots of fields array points to each of the NF words (which are null-terminated) line contains the line number of this line Returns NS field as its return value Returns 1 when reaches end of file void jettison_input_struct(is) Closes file and frees IS
12 Example Using Fields: printwords.c #include < stdio.h > #include "fields.h" main(int argc, char **argv) { IS is; int i; if (argc!= 2) { fprintf(stderr, "usage: printwords filename\n"); exit(1); is = new_inputstruct(argv[1]); if (is == NULL) { perror(argv[1]); exit(1); while(get_line(is) >= 0) { for (i = 0; i < is->nf; i++) { printf("%d: %s\n", is->line, is->fields[i]); jettison_inputstruct(is); exit(0); Example input file (rex.in): June: Hi... I missed you! Rex: Same here! You're all I could think about! June: I was? Output: UNIX> printwords rex.in 1: June: 1: Hi 1:... 1: I 1: missed 1: you! 2: Rex: 2: Same 2: here! 2: You're 2: all 2: I 2: could 2: think 2: about! 3: June: 3: I 3: was?
13 What wrong with this code? (Attempts to print out first word on next-to-last line) #include < stdio.h > #include "fields.h" main(int argc, char **argv) { IS is; int i; char *penultimate_word; char *last_word; is = new_inputstruct(argv[1]); if (is == NULL) { perror(argv[1]); exit(1); penultimate_word = NULL; last_word = NULL; while(get_line(is) >= 0) { penultimate_word = last_word; if (is->nf > 0) { last_word = is->fields[0]; else { last_word = NULL; Hint: For the following input file, June: Hi... I missed you! Rex: Same here! You're all I could think about! June: I was? this code prints out: UNIX> badword rex.in if (argc!= 2) June: { fprintf(stderr, "usage: badword filename\n"); exit(1); if (penultimate_word!= NULL) printf("%s\n", penultimate_word); jettison_inputstruct(is); exit(0);
14 What wrong with this code? (Attempts to print out first word on next-to-last line) #include < stdio.h > #include "fields.h" main(int argc, char **argv) { IS is; int i; char *penultimate_word; char *last_word; if (argc!= 2) { fprintf(stderr, "usage: badword filename\n"); exit(1); is = new_inputstruct(argv[1]); if (is == NULL) { perror(argv[1]); exit(1); Problem: get_line() doesn t allocate memory; penultimate_word and last_word point to same thing REMEMBER: Only new_inputstruct() mallocs memory penultimate_word = NULL; last_word = NULL; while(get_line(is) >= 0) { penultimate_word = last_word; if (is->nf > 0) { last_word = is->fields[0]; else { last_word = NULL; if (penultimate_word!= NULL) printf("%s\n", penultimate_word); jettison_inputstruct(is); exit(0);
15 We ve looked at the fields Interface; Now, let s look at the Implementation #include <stdio.h> #include "fields.h" #define talloc(ty, sz) (ty *) malloc (sz * sizeof(ty)) #define strdup(s) ((char *) strcpy(talloc(char, strlen(s)+1), s)) static IS make_inputstruct(filename, key) char *filename; char *key; /* "f" for regular file or stdin if filename is NULL */ /* "p" if filename is a command for popen */ { IS is; int file; if (strcmp(key, "f") == 0) { file = 1; else if (strcmp(key, "p") == 0) { file = 0; else { return NULL; is = talloc(struct inputstruct, 1); is->text1[maxlen-1] = '\0'; is->nf = 0; is->line = 0; if (filename == NULL) { is->name = "stdin"; is->f = stdin; else { is->name = filename; is->file = file; if (file) { is->f = fopen(filename, "r"); else { is->f = popen(filename, "r"); if (is->f == NULL) { free(is); return NULL; return is;
16 fields Implementation, con t. IS new_inputstruct(filename) /* use NULL for stdin. Calls malloc */ char *filename; { return make_inputstruct(filename, "f"); void jettison_inputstruct(is) IS is; { if (is->f!= stdin) { if (is->file) { fclose(is->f); else { pclose(is->f); free(is); return;
17 fields Implementation, con t. int get_line(is) IS is; { int i, len; int f; char *tmp; char lastchar; char *line; is->nf = 0; if (fgets(is->text1, MAXLEN-1, is->f) == NULL) { is->nf = -1; return -1; is->line++; strcpy(is->text2, is->text1); line = is->text2; lastchar = ' '; for (i = 0; line[i]!= '\0' && i < MAXLEN-1; i++) { if (isspace(line[i])) { lastchar = line[i]; line[i] = '\0'; else { if (isspace(lastchar)) { is->fields[is->nf] = line+i; is->nf++; lastchar = line[i]; return is->nf;
18 Next tool: Jval (defined in jval.h) Jval is a big union (8 bytes long) Recall union in C: Memory location that is shared by 2 or more different variables Example: union utype { short int i; char ch; ; Remember: union can t hold multiple types at the same time. Your program can treat the data as any of the data types (one at a time)
19 Here s the Jval definition typedef union { int i; long l; float f; double d; void *v; char *s; char c; unsigned char uc; short sh; unsigned short ush; unsigned int ui; int iarray[2]; float farray[2]; char carray[8]; unsigned char ucarray[8]; Jval; Use Jval when defining generic data structure, such as lists and trees
20 How to use Jvals? Easy: Jval j; j.i = 12; But another way is also helpful: Use constructor functions
21 Let s sidetrack a bit, and define Constructor functions Makes life easier in some situations (to be discussed later) Will be used extensively when we get to C++ Definition of constructor function: A function that initializes an object when it is created. Has no explicit return type (Opposite of a constructor function destructor)
22 Now, Jval Constructor Functions extern Jval new_jval_i(int); extern Jval new_jval_f(float); extern Jval new_jval_d(double); extern Jval new_jval_v(void *); extern Jval new_jval_s(char *); Jval j; j = new_jval_i(12); Now, j.i is 12.
23 Jval Accessor Functions Like constructor functions, accessor functions can make life easier (we ll see why later in the course) extern int jval_i(jval); extern long jval_l(jval); extern float jval_f(jval); extern double jval_d(jval); extern void *jval_v(jval); extern char *jval_s(jval); extern char jval_c(jval);... jval_i(j) is same thing as j.i
24 JNULL Global variable defined in jval.h Use when you would use NULL for char * or void *
25 Warning about Jvals! Purpose is to make general-purpose structures such as doubly-linked lists and red-black trees as flexible and efficient as possible DO NOT USE Jvals when a simpler data structure suffices: main() { Jval total; Jval j; Jval n; BAD CODE: n.i = 0; total.i = 0; while (scanf("%d", &(j.i)) == 1) { total.i += j.i; n.i++; total.d = ((double) total.i)/((double) n.i); printf("average = %lf\n", total.d);
26 We ve looked at the Jval Interface; Now, let s look at the Implementation Jval new_jval_i(int i) { Jval j; j.i = i; return j; Jval new_jval_l(long l) { Jval j; j.l = l; return j; Jval new_jval_f(float f) { Jval j; j.f = f; return j; Jval new_jval_d(double d) { Jval j; j.d = d; return j; Others are similar
27 Intermission: Corny Jokes Real programmers don t comment their code If it was hard to write, it should be hard to understand Real Programmers don't write specs Users should consider themselves lucky to get any programs that work at all -- and take what they get. Real programmers don t document Documentation is for wimps who can t read the listings or the object deck Just kidding!! (This doesn t apply to CS302 students!)
28 More intermission How the programmer wrote it How the Business Consultant described it How the project was documented
29 Next tool: Doubly-linked list library dllist.c, dllist.h First, refresher on doubly-linked lists: First, empty list dll: dll ptr to next node ptr to previous node value of this node =? Sentinel node (I.e., first node on the list; does not contain application data
30 Refresher on Doubly-linked lists Now, append a node to end, with value 8 dll ptr to next node ptr to previous node value of this node =? Sentinel node ptr to next node ptr to previous node value of this node = 8
31 Refresher on Doubly-linked lists Now, insert a node (with value 13) before the node we just added dll ptr to next node ptr to next node ptr to next node ptr to previous node ptr to previous node ptr to previous node value of this node value of this node value of this node =? = 13 = 8 Sentinel node
32 API for doubly-linked lists (dllist.h) typedef struct dllist { struct dllist *flink; /* Forward Pointer to next node */ struct dllist *blink; /* Backward Ptr to previous node */ Jval val; *Dllist; Plus, 14 procedures
33 Dllist procedures Dllist new_dllist(): Allocates and returns a new doubly linked list. free_dllist(dllist l): Destroys the list, calling free() on all allocated memory in the list. The list does not have to be empty. dll_prepend(dllist l, Jval val): Adds a new node at the beginning of the list. This node's value is val. Has no return value. dll_append(dllist l, Jval val): Adds a new node at the end of the list. This node's value is val. Has no return value. dll_insert_b(dllist n, Jval val): Adds a new node to the list right before the specified node. This node's value is val. dll_insert_a(dllist n, Jval val): Adds a new node to the list right after the specified node. This node's value is val.
34 Dllist procedures (con t) Dllist dll_nil(dllist l): Returns a pointer to the nil (sentinel) node for the list. You can think of nil as a node with no value, that begins and ends the list. Since l points to the sentinel node, dll_nil returns l. You don't need to call dll_nil() to access the sentinel node. You can just use l, although it makes your code more readable if you use dll_nil(). Dllist dll_first(dllist l): Returns a pointer to the first node in the list. If the list is empty, this returns the sentinel. As with dll_nil(), you don't need to call dll_first(l) -- you can just use l->flink. Dllist dll_last(dllist l): Returns a pointer to the last node in the list. If the list is empty, this returns the sentinel. As with dll_nil(), you don't need to call dll_last(l) -- you can just use l->blink.
35 Dllist procedures (con t) Dllist dll_next(dllist n): Returns a pointer to the next node in the list after n. If n is the last node on the list, then dll_next(n) returns the sentinel. As with dll_first(), you don't need to call dll_next(n) -- you can just use n->flink. Dllist dll_prev(dllist n): Returns a pointer to the previous node in the list before n. If n is the first node on the list, then dll_prev(n) returns the sentinel. As with dll_last(), you don't need to call dll_prev(n) -- you can just use n->blink. int dll_empty(dllist l): Returns whether l is empty. Jval dll_val(dllist n): Returns node n's val field. Again, you don't need to use this, but sometimes it comes in handy. int dll_delete_node(dllist n): Deletes and frees node n.
36 Also: 2 macros, for traversing lists Forward traversing: #define dll_traverse(ptr, list) \ for (ptr = (list)->flink; ptr!= (list); ptr = ptr- >flink) Reverse traversing: #define dll_rtraverse(ptr, list) \ for (ptr = (list)->blink; ptr!= (list); ptr = ptr- >blink) ptr and list should both be of type Dllist
37 Example using the dllist tools: What does this code do? #include < stdio.h > #include < string.h > #include "fields.h" #include "dllist.h" main(int argc, char ** argv) { IS is; Dllist l; Dllist tmp; if (argc!= 2) { fprintf(stderr, usage: pgmname inputfile \n); exit(1); is = new_inputstruct(argv[1]); if (is == NULL) { perror(argv[1]); exit(1); l = new_dllist(); while (get_line(is) >= 0) { dll_append(l, new_jval_s(strdup(is->text1))); dll_rtraverse(tmp, l) printf("%s", jval_s(tmp->val)); jettison_inputstruct(is);
38 Example using the dllist tools: What does this code do? #include < stdio.h > #include < string.h > #include "fields.h" #include "dllist.h" main(int argc, char ** argv) { IS is; Dllist l; Dllist tmp; It prints out the input lines in reverse order if (argc!= 2) { fprintf(stderr, usage: pgmname inputfile \n); exit(1); is = new_inputstruct(argv[1]); if (is == NULL) { perror(argv[1]); exit(1); l = new_dllist(); while (get_line(is) >= 0) { dll_append(l, new_jval_s(strdup(is->text1))); dll_rtraverse(tmp, l) printf("%s", jval_s(tmp->val)); jettison_inputstruct(is);
39 Another example using the dllist tools: What does this code do? #include < stdio.h > #include < string.h > #include "fields.h" #include "dllist.h" main(int argc, char **argv) { IS is; int n; Dllist l; Dllist tmp; if (argc!= 2) { fprintf(stderr, "usage: dlltail n inputfile\n"); exit(1); n = atoi(argv[1]); if (n < 0) { fprintf(stderr, "usage: n must be >= 0\n"); exit(1); is = new_inputstruct(argv[2]); /* Insert error checking here */ l = new_dllist(); while (get_line(is) >= 0) { dll_append(l, new_jval_s(strdup(is->text1))); if (is->line > n) { tmp = dll_first(l); free(jval_s(dll_val(tmp))); dll_delete_node(tmp); dll_traverse(tmp, l) printf("%s", jval_s(tmp->val)); jettison_inputstruct(is);
40 Another example using the dllist tools: What does this code do? #include < stdio.h > #include < string.h > #include "fields.h" #include "dllist.h" It prints out the last n lines of the input main(int argc, char **argv) { IS is; int n; Dllist l; Dllist tmp; if (argc!= 2) { fprintf(stderr, "usage: dlltail n inputfile\n"); exit(1); n = atoi(argv[1]); if (n < 0) { fprintf(stderr, "usage: n must be >= 0\n"); exit(1); is = new_inputstruct(argv[2]); /* Insert error checking here */ l = new_dllist(); while (get_line(is) >= 0) { dll_append(l, new_jval_s(strdup(is->text1))); if (is->line > n) { tmp = dll_first(l); free(jval_s(dll_val(tmp))); dll_delete_node(tmp); dll_traverse(tmp, l) printf("%s", jval_s(tmp->val)); jettison_inputstruct(is);
41 We ve looked at the dllist Interface; Now, let s look at the Implementation Dllist new_dllist() { Dllist d; d = (Dllist) malloc (sizeof(struct dllist)); d->flink = d; d->blink = d; return d; dll_empty(dllist l) { return (l->flink == l); free_dllist(dllist l) { while (!dll_empty(l)) { dll_delete_node(dll_first(l)); free(l); #define dll_first(d) ((d)->flink) #define dll_next(d) ((d)->flink) #define dll_last(d) ((d)->blink) #define dll_prev(d) ((d)->blink) #define dll_nil(d) (d)
42 dllist Implementation, con t. dll_insert_b(dllist node, Jval v) /* Inserts before a given node */ { Dllist new; new = (Dllist) malloc (sizeof(struct dllist)); new->val = v; new->flink = node; new->blink = node->blink; new->flink->blink = new; new->blink->flink = new; dll_insert_a(dllist n, Jval val) /* Inserts after a given node */ { dll_insert_b(n->flink, val); dll_append(dllist l, Jval val) /* Inserts at the end of the list */ { dll_insert_b(l, val); dll_prepend(dllist l, Jval val) /* Inserts at beginning of list */ { dll_insert_b(l->flink, val); dll_delete_node(dllist node) /* Deletes an arbitrary iterm */ { node->flink->blink = node->blink; node->blink->flink = node->flink; free(node);
43 That s all, folks Remember: 1 st Labs meet this week (tomorrow and Friday) Attendance required for 1 st lab!! Your homework: Keep working on Lab 1!! Due Friday, Sept. 9. Read 4 handouts for today, and work examples contained in them: See Schedule/Readings/Notes link for today: Before class next time: Read handout for next class on Red-Black Tree Library (JRB): See Schedule/Readings/Notes link for today:
Recitation 2/18/2012
15-213 Recitation 2/18/2012 Announcements Buflab due tomorrow Cachelab out tomorrow Any questions? Outline Cachelab preview Useful C functions for cachelab Cachelab Part 1: you have to create a cache simulator
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationTHE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming
THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY ISA 563: Fundamentals of Systems Programming Announcements Homework 2 posted Homework 1 due in two weeks Typo on HW1 (definition of Fib. Sequence incorrect)
More informationReview: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc
CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationCSE 303 Midterm Exam
CSE 303 Midterm Exam October 29, 2008 Name Sample Solution The exam is closed book, except that you may have a single page of hand written notes for reference. If you don t remember the details of how
More informationEL2310 Scientific Programming
Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files
More informationCS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco
CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level
More informationFloating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions
Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point
More informationMemory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)
Memory Allocation Memory What is memory? Storage for variables, data, code etc. How is memory organized? Text (Code) Data (Constants) BSS (Global and static variables) Text Data BSS Heap Stack (Local variables)
More informationLecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.
Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special
More informationSingly linked lists in C.
Singly linked lists in C http://www.cprogramming.com/tutorial/c/lesson15.html By Alex Allain Linked lists are a way to store data with structures so that the programmer can automatically create a new place
More informationECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.
ECE 264 Exam 2 6:30-7:30PM, March 9, 2011 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise you will receive a 1-point penalty.
More information25.2 Opening and Closing a File
Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:
More information2009 S2 COMP File Operations
2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations
More informationIntroduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Sean Ogden Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Ayush Dubey Cornell CS 4411, August 30, 2013 Administrative Information
More informationGeneric programming anhtt-fit@mail.hut.edu.vn dungct@it-hut.edu.vn Introduction Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations.
More informationCSC209H Lecture 3. Dan Zingaro. January 21, 2015
CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without
More informationContents. A Review of C language. Visual C Visual C++ 6.0
A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source
More information211: Computer Architecture Summer 2016
211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:
More informationCS 2113 Software Engineering
CS 2113 Software Engineering Do this now!!! From C to Java git clone https://github.com/cs2113f18/c-to-java.git cd c-to-java./install_java Professor Tim Wood - The George Washington University We finished
More informationToday s Learning Objectives
Today s Learning Objectives 15-123 Systems Skills in C and Unix We will Review ints and modular arithmetic Learn basic Data types and Formats How Conditionals and loops work How Arrays are defined, accessed,
More informationCS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2
CS32 - Week 2 Umut Oztok July 1, 2016 Arrays A basic data structure (commonly used). Organize data in a sequential way. Arrays A basic data structure (commonly used). Organize data in a sequential way.
More informationEL2310 Scientific Programming
Lecture 12: Memory, Files and Bitoperations (pronobis@kth.se) Overview Overview Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations Wrap Up Lecture
More informationIntroduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers
Introduction to C Geared toward programmers Ayush Dubey Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Zhiyuan Teo Cornell CS 4411, August 31, 2012 Administrative Information Outline
More informationHeap Arrays and Linked Lists. Steven R. Bagley
Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our
More informationFile Access. FILE * fopen(const char *name, const char * mode);
File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header
More informationC++ for Java Programmers
Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even
More informationRecitation #11 Malloc Lab. November 7th, 2017
18-600 Recitation #11 Malloc Lab November 7th, 2017 1 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than 32 bit Encourages
More informationCSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-43 Exam Review February, 01 Presented by the RIT Computer Science Community http://csc.cs.rit.edu C Preprocessor 1. Consider the following program: 1 # include 3 # ifdef WINDOWS 4 # include
More informationAPT Session 4: C. Software Development Team Laurence Tratt. 1 / 14
APT Session 4: C Laurence Tratt Software Development Team 2017-11-10 1 / 14 http://soft-dev.org/ What to expect from this session 1 C. 2 / 14 http://soft-dev.org/ Prerequisites 1 Install either GCC or
More informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More informationTwo s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011
Two s Complement Review CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part I) Instructor: Michael Greenbaum http://inst.eecs.berkeley.edu/~cs61c/su11 Suppose we had
More informationECE264 Fall 2013 Exam 3, November 20, 2013
ECE264 Fall 2013 Exam 3, November 20, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.
More informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Functions Similar to (static) methods in Java without the class: int f(int a, int
More informationArrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga
Arrays and Strings Antonio Carzaniga Faculty of Informatics Università della Svizzera italiana February 23, 2015 Outline General memory model Definition and use of pointers Invalid pointers and common
More informationLab Exam 1 D [1 mark] Give an example of a sample input which would make the function
CMPT 127 Spring 2019 Grade: / 20 First name: Last name: Student Number: Lab Exam 1 D400 1. [1 mark] Give an example of a sample input which would make the function scanf( "%f", &f ) return -1? Answer:
More informationare all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.
CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,
More informationRicardo Rocha. Department of Computer Science Faculty of Sciences University of Porto
Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()
More informationstructs as arguments
Structs A collection of related data items struct record { char name[maxname]; int count; ; /* The semicolon is important! It terminates the declaration. */ struct record rec1; /*allocates space for the
More informationData Structures and Algorithms for Engineers
04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University
More informationEECE.2160: ECE Application Programming
Fall 2017 Programming Assignment #10: Doubly-Linked Lists Due Monday, 12/18/17, 11:59:59 PM (Extra credit ( 5 pts on final average), no late submissions or resubmissions) 1. Introduction This assignment
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationCSC 270 Survey of Programming Languages. Input and Output
CSC 270 Survey of Programming Languages C Lecture 8 Input and Output Input and Output C supports 2 different I/O libraries: buffered (higher level functions supported by ANSI standards) unbuffered (lower-level
More informationThese problems are provided to you as a guide for practice. The questions cover important concepts covered in class.
Midterm Written Exam Practice Midterm will cover all concepts covered up to the midterm exam. Concepts of arrays, LL s, pointers (*,**,***), malloc, calloc, realloc, function pointers, Hash tables will
More informationIntroduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or
More informationHere's how you declare a function that returns a pointer to a character:
23 of 40 3/28/2013 10:35 PM Violets are blue Roses are red C has been around, But it is new to you! ANALYSIS: Lines 32 and 33 in main() prompt the user for the desired sort order. The value entered is
More informationIntroduction to C. CS2023 Winter 2004
Introduction to C CS2023 Winter 2004 Outcomes: Introduction to C After the conclusion of this section you should be able to Recognize the sections of a C program Describe the compile and link process Compile
More informationSOFTWARE Ph.D. Qualifying Exam Spring Consider the following C program which consists of two function definitions including the main function.
(i) (5 pts.) SOFTWARE Ph.D. Qualifying Exam Spring 2018 Consider the following C program which consists of two function definitions including the main function. #include int g(int z) { int y
More informationIntroduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers
Introduction to C Geared toward programmers Zhiyuan Teo Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Robert Escriva Cornell CS 4411, August 26, 2011 1 Administrative Information 2 Why C? 3
More informationunsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables
Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char
More informationHTML Editor for UNIX Terminals in C
University of Tennessee, Knoxville Trace: Tennessee Research and Creative Exchange University of Tennessee Honors Thesis Projects University of Tennessee Honors Program 5-1999 HTML Editor for UNIX Terminals
More informationC BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.
C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,
More informationCSE 333 SECTION 3. POSIX I/O Functions
CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the
More informationMidterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:
Page 1 of 8 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2015 Midterm Examination # 2 Wednesday, March 18, 2015 ANSWERS Duration of examination: 75 minutes STUDENT
More informationPrograms. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems
Programs CSCI 4061 Introduction to Operating Systems C Program Structure Libraries and header files Compiling and building programs Executing and debugging Instructor: Abhishek Chandra Assume familiarity
More informationLecture 8: Structs & File I/O
....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationFile IO and command line input CSE 2451
File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to
More informationCS 261 Fall Mike Lam, Professor. Structs and I/O
CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful
More informationTopic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)
Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function
More informationProblem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.
Problem 1 Recall the definition of root in project 1. (The declaration of struct entrynode appears below.) struct entrynode * root; Give the type of each of the following expressions. The answer may be
More informationCS 1713 Introduction to Programming II
CS 1713 Introduction to Programming II Spring 2014 Midterm 2 -- April 24, 2014 You have 75 min. Good luck. You can use the 2-page C reference card posted in the class web page. Name: Score:./100 Background
More informationContent. Input Output Devices File access Function of File I/O Redirection Command-line arguments
File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by
More informationComputer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview
Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: C and Unix Overview This course is about computer organization, but since most of our programming is
More informationWeek 5, continued. This is CS50. Harvard University. Fall Cheng Gong
This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!
More informationAnnouncements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17
Announcements Lecture 04b Sept. 14 th, 2017 Midterm #1: Sept. 26 th (week from Tuesday) Code distributed one week from today PA2 test cases & answers posted Quiz #4 next Tuesday (before class) PA3 due
More informationTutorial 1: Introduction to C Computer Architecture and Systems Programming ( )
Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough
More informationPointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.
Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;
More informationQuick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.
1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #8 Feb 27 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline More c Preprocessor Bitwise operations Character handling Math/random Review for midterm Reading: k&r ch
More informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More informationCall The Project Dynamic-Memory
1 2 2 Call The Project Dynamic-Memory 4 4 Copy-Paste Main # include "Utilities.hpp" int main(int argc, char * argv[]) { short int *PtrNo; (*PtrNo) = 5; printf ("(*PtrNo) = %d\n", (*PtrNo)); } getchar();
More informationExercise Session 3 Systems Programming and Computer Architecture
Systems Group Department of Computer Science ETH Zürich Exercise Session 3 Systems Programming and Computer Architecture Herbstsemester 2016 Agenda Review of Exercise 2 More on C-Programming Outlook to
More informationELEC 377 C Programming Tutorial. ELEC Operating Systems
ELE 377 Programming Tutorial Outline! Short Introduction! History & Memory Model of! ommon Errors I have seen over the years! Work through a linked list example on the board! - uses everything I talk about
More informationHomework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08
Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08 For your solutions you should submit a hard copy; either hand written pages stapled together or a print out of a typeset document
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationLab Exam 1 D [1 mark] Give an example of a sample input which would make the function
Grade: / 20 Lab Exam 1 D500 1. [1 mark] Give an example of a sample input which would make the function scanf( "%f", &f ) return 0? Answer: Anything that is not a floating point number such as 4.567 or
More informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationCarnegie Mellon. Cache Lab. Recitation 7: Oct 11 th, 2016
1 Cache Lab Recitation 7: Oct 11 th, 2016 2 Outline Memory organization Caching Different types of locality Cache organization Cache lab Part (a) Building Cache Simulator Part (b) Efficient Matrix Transpose
More informationWeek 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430
Week 2 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430 1 Why is the Shell Important? Shells provide us with a way to interact with the core system Executes programs on
More informationCS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: April 5, 11:30 PM
CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: April 5, 11:30 PM Goals To understand the nuances of building a memory allocator. To create a shared library. Background
More informationHeap Arrays. Steven R. Bagley
Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,
More informationLab 4: Tracery Recursion in C with Linked Lists
Lab 4: Tracery Recursion in C with Linked Lists For this lab we will be building on our previous lab at the end of the previous lab you should have had: #include #include char * make_string_from
More informationArrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]
(November 10, 2009 2.1 ) Arrays An array is a collection of several elements of the same type. An array variable is declared as type array name[size] I The elements are numbered as 0, 1, 2... size-1 I
More informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationCS 220: Introduction to Parallel Computing. Input/Output. Lecture 7
CS 220: Introduction to Parallel Computing Input/Output Lecture 7 Input/Output Most useful programs will provide some type of input or output Thus far, we ve prompted the user to enter their input directly
More informationBasic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Basic C Programming Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Announcements Exam 1 (20%): Feb. 27 (Tuesday) Tentative Proposal Deadline:
More informationCS 61c: Great Ideas in Computer Architecture
Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address
More informationCS4023 Week06 Lab Exercise
CS4023 Week06 Lab Exercise Lab Objective: In this week s lab we will look at writing a program that reads a large matrix of numbers and then reports all numbers that are equal to a reference value (or
More informationCS113: Lecture 5. Topics: Pointers. Pointers and Activation Records
CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",
More informationTutorial 1 C Tutorial: Pointers, Strings, Exec
TCSS 422: Operating Systems Institute of Technology Spring 2017 University of Washington Tacoma http://faculty.washington.edu/wlloyd/courses/tcss422 Tutorial 1 C Tutorial: Pointers, Strings, Exec The purpose
More informationCS 237 Meeting 19 10/24/12
CS 237 Meeting 19 10/24/12 Announcements 1. Midterm: New date: Oct 29th. In class open book/notes. 2. Try to complete the linear feedback shift register lab in one sitting (and please put all the equipment
More information1. Introduction. 2. Deliverables
16.216: ECE Application Programming Summer 2014 Programming Assignment #10: Doubly-Linked Lists Due Friday, 6/27/14, 12:00 PM (noon) NO LATE ASSIGNMENTS 1. Introduction This assignment deals with the combination
More informationSolution for Data Structure
Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT
More informationmalloc(), calloc(), realloc(), and free()
1 next CITS2002 CITS2002 schedule Dynamic data structures Initially, we focused on scalar and array variables, whose size is known at compile-time. More recently, we've focused on arrays of values, whose
More informationCS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren
CS32 Discussion Sec.on 1B Week 2 TA: Zhou Ren Agenda Copy Constructor Assignment Operator Overloading Linked Lists Copy Constructors - Motivation class School { public: }; School(const string &name); string
More informationCS1003: Intro to CS, Summer 2008
CS1003: Intro to CS, Summer 2008 Lab #07 Instructor: Arezu Moghadam arezu@cs.columbia.edu 6/25/2008 Recap Pointers Structures 1 Pointer Arithmetic (exercise) What do the following return? given > char
More information