Spring 2007 May 16, 2007 CS107 Midterm Solution

Size: px
Start display at page:

Download "Spring 2007 May 16, 2007 CS107 Midterm Solution"

Transcription

1 CS107 Handout 26S Spring 2007 May 16, 2007 CS107 Midterm Solution Problem 1: Color Theory (15 points: ) Consider the following struct definitions: typedef struct palette short *lavender; char indigo[4]; struct palette *peach[2]; palette; line 1 line 2 line 3 static palette **swatch(palette *ecru, int mint); static int colorwheel(palette ruby, int seafoam) seafoam = ruby.lavender[ruby.indigo[3]]; ruby.peach[0] += ((palette *)ruby.indigo)->lavender[2]; return swatch(&ruby, 8) - ruby.peach; Generate code for the entire colorwheel function. Be clear about what assembly code corresponds to what line. You have this and the next two pages for your work. seafoam // line 1 R1 = M[SP + 4]; // load ruby.lavender R2 =.1 M[SP + 11]; // load ruby.indigo[3] ruby.peach[1] ruby.peach[0] R3 = 2 * R2; // scale by sizeof(short) ruby.indigo[0...3] R4 = R1 + R3; // full address of rhs short R5 =.2 M[R4]; // pull in rhs short ruby.lavender M[SP + 20] = R5; // write rhs val to seafoam saved PC // line 2 SP R1 = M[SP + 12]; // load old lhs R2 = M[SP + 8]; // load lavender of pretend struct starting at &ruby.indigo[0] R3 =.2 M[R2 + 4]; // load third short in short array starting at R2 R4 = R3 * 16; // scale offset in R3 by sizeof(palette) R5 = R1 + R4; // compute new value for lhs M[SP + 12] = R5; // flush to lhs space // line 3 R1 = SP + 4; // compute &ruby SP = SP 8; // make space to two parameters M[SP] = R1; // press ecru M[SP +4] = 8; // press mint CALL <swatch> // jump away, expecting RV to be populated by a palette ** SP = SP + 8; // deallocate params R2 = SP + 12; // load &ruby.peach[0] R3 = RV R2; // compute difference in raw bytes RV = R3 / 4; // divide by sizeof(palette *) and populate RV RET;

2 2 Criteria for Problem 1 (written for the staff, visible to the students for transparency) Criteria for Line 1: 5 points Properly pulling the lavender field: 1 point Properly pulling the third character in indigo: 1 point Properly scaling the offset and computing the location of the relevant short: 1 point Properly loading the short: 1 point Properly writing the four byte version of that short to seafoam: 1 point 0.5 point deductions are fine, and we double ding for the same error, but we don t triple ding, so make sure between all three lines you cap similar deductions re.1/.2, and illegal assembly code instructions at 1 point total. Line 2 is 5 points Properly grabbing lavender field of pretend struct using the proper number of dereferences: 2 points (this is 2 or 0, because it s difficult to get this right, and it s clear from the sample midterm and all the examples that this is challenging.) Properly grabbing third short: 1 point Properly scaling it by sizeof(palette): 1 point Properly identifying, loading, and eventually updating the correct lhs l-value: 1 point Line 3 is 5 points Allocating and deallocating the right amount of space for the params: 1 point Populates param space within correct values, in correct order: 1 point Properly computes the raw number of bytes sitting in between return value and &ruby.peach[0]: 1 point Scales back by sizeof(palette *): 1 point Populates RV before returning: 1 point

3 3 Problem 2: packpackets (15 points) You re to write code that traverses a linked list of custom nodes and builds a dynamically allocated array of bytes large enough to store the meaningful data held by the linked list. Each node stores one or more packets of raw information, where each packet is preceded by a two-byte short stating the length (in bytes) of the packet that follows it. The end of the packet sequence is marked by a two-byte zero, and the four bytes after that store the address of the next node in the list (or NULL, if the node is the last in the list). The following node contains three packets of length 20, 10, and 30 bytes, in that order. The number of bytes making up the entire node is You re to write a function called packpackets that, given the address of the first node in such a list, builds a dynamically allocated byte array where all packets in the linked list are replicated verbatim, one after another, in the same order they appear in the list. So, given the following list: NULL your packpackets function would return the address of the first byte of this dynamically allocated figure: Here are some constraints I m imposing on your implementation. The address passed to packpackets is the address of the first short storing the number of bytes making up the first packet in the first node. Each node alternates between shorts and packets. A two-byte zero marks the end of the packet sequence in any given node. Every node ends with a four-byte pointer identifying the location of the next node in the list. You should implement this function iteratively, and your algorithm should accomplish everything in exactly one traversal. This requires you to call realloc for each packet you encounter during your one traversal. [Tip: When NULL is passed as the first argument to realloc, realloc just calls malloc on your behalf.] This artificial constraint is being imposed so that I can test your understanding of realloc. For simplicity, you may assume the list contains at least one node, and that each node contains at least one packet. You needn t worry about any alignment restrictions at all. You shouldn t free or modify the original list in any way. Use the next page for your implementation. Feel free to tear this page out.

4 4 Problem 2 Continued /** * Function: packpackets * * Builds a contiguous array version of the packet list structure according * to the explanations provided on the prior page. The parameter passed * is of type short *, because the first meaningful piece of information * stored in the list is a two-byte short. The return value is of type * void *, because the implementation has no type information about the * packet data. */ void *packpackets(short *list) void *image = NULL; int imagesize = 0; while (list!= NULL) int packetsize = *list++; char *data = list; if (packetsize > 0) image = realloc(image, imagesize + packetsize); memcpy((char *) image + imagesize, data, packetsize); imagesize += packetsize; list = (short *)(data + packetsize); else list = *(short **)data; // list = *(void **)data would work too return image; Criteria for Problem 2: 15 points Successfully creates the initial segment, either as NULL of 0 bytes before any packets are processed, or via a standalone malloc call that s special-cased up front: 2 points Correctly pulls the size of the next packet: 1 point Correctly identifies the location of the data image: 1 point Correctly calls realloc to resize the block to make room for the new packet: 3 points o o o Passes in the correct size in bytes as the second argument: 1 point Catches the return value (assert not required): 1 point Understands that realloc frees the old block and memcpy s the material so the client doesn t have to: 1 point Keeps track of the current image length: 1 point Properly advanced to the next packet size in the node: 2 points o 1 point for correct pointer arithmetic with necessary casting (note that my data is a char *, o while there s might be a void *, thereby requiring a cast.) 1 point for any additional casts required of the variable assignment. Properly detects end-on-node condition: 1 point Properly casts and dereferences to advance to the next node: 1 point Handles NULL: 1 point Returns image: 1 point Points dedicated to other issues we can t anticipate: 1 point (point mat be used to deduct for spurious ampersanding, for instance)

5 5 Problem 3: Python (15 points) Python provides support for objects just like C++ and Java do, but its implementation model is different. Rather than requiring that all fields be stated at compile time, Python allows its objects to take on new fields as the code executes. Here s how a Python object might grow to represent a Stanford student: student = # initialized to be an empty object student['name'] = 'Edward Requenez' student['numunits'] = 15 student['gpa'] = student['friends'] = ['Bill','Will','Sawyer','Alex','Daniel'] student['hometown'] = # initialized to be an empty object student['hometown']['city'] = 'Dallas' student['hometown']['state'] = 'Texas' student['hometown']['zip'] = You don t need to know Python to know what the code s trying to do. The coder decided to model some Stanford student as a Python object with five properties. Each accommodates a value of a different data type. Python doesn t require that object structure be stated up front. We re going to assume that all Python values whether they re top-level primitives or fields within an aggregate record, are implemented in terms of the following pure C enum and struct definitions: typedef enum Integer, Float, String, Array, Object PythonType; typedef struct const char *id; PythonType type; char value[4]; PythonPair; Don t be misled PythonPair's third field. It looks like it stores a small number of characters, but it actually sits there as a general-purpose four-byte register of sorts. We ve done enough C casting and reinterpretation of bit patterns to know how to exploit that little value array for all it s worth. Sometimes we used those four bytes to store an integer, as with: numdalmations = 101 For other primitives, we use the four bytes to store something else: pi = ; contestant = 'Sanjaya Malakar' The value array contains the bit pattern of either a four-byte integer, a four-byte float or a four-byte pointer to a null-terminated char array. We rely on the type field to figure out what those four bytes are storing Sanjaya Malakar\0 Integer Float String numdalmations\0 pi\0 contestant\0

6 And guess what? Python objects and arrays are backed by the infamous hashset and vector types from Assignments 3 and 4. 6 When a field is an array, the value array stores the address of a vector of PythonPairs, where the id fields just store NULL as a sentinel that neither the id fields nor the colons need to be printed. When a field is an inner object, value stores the address of a hashset. The hashset is the in-memory representation of a Python object that s been built up to include an arbitrarily large number of properties. Those properties are stored as PythonPairs in a hashset, and provided you allow for some of those PythonPairss to store vector *s and hashset *s, you have the means to recursively build Python objects with primitives, Python arrays, and Python objects as fields. Given the address of a hashset of PythonPairss, you re going to write a function called serializeobject that synthesizes the C string representation of the entire object, just like Python would. Primitives are serialized as you d expect, though all strings constants are delimited by single quotes. Arrays are square-bracket-delimited, comma-separated lists. The student object from above looks like this: 'name':'ed Requenez','numUnits':15,'gpa':3.966, 'friends':['bill','will','sawyer','alex','daniel',], 'hometown':'city':'dallas','state':'texas','zipcode':75209,, A full object s serialization is delimited by curly braces. Between those curly braces is a comma-separated list of id/value pairs. The identifiers are always strings with singe quotes. Each value gets published either as the primitive it is, or recursively as the array or sub-object it s addressing. The identifiers are separated from their values by colons, there s no intervening white space, and it s fine to have a trailing comma after the last entry within an array of object serialization. This is a difficult question that necessarily uses HashSetMap. And because HashSetMapFunction and VectorMapFunction have the same prototype, it makes sense use VectorMap to serialize Python arrays. You may assume the existence of convenience functions called intcpy and floatcpy, which operate much like strcpy, in that they place '\0'-terminated C strings in the specified buffer. In this case the strings they place are the textual equivalents of integers and floats. void intcpy(char *dest, int value); // does not allocate memory void floatcpy(char *dest, float value); // does not allocate memory Use the space provided on the next three pages for your implementation. You re more than encouraged to decompose your solution. Don t orphan any memory. For simplicity, you may assume that the full serialization is less than 8192 characters (a nice power of 2), but the dynamically allocated string that s ultimately returned must use only as much memory as is absolutely necessary to store the serialization.

7 7 Problem 3 Continued /** * Function: serializeobject * * Traverses the hashset representation of a Python object and * synthesizes a single, dynamically allocated C string storing the * textual representation of the entire object. */ char *serializeobject(hashset *object) char text[8192] = '\0'; // 'master' buffer that's threaded through traversal appendobject(text, object); return strdup(text); // take persistent snapshot of accumuation void appendstring(char *text, const char *str) strcat(text, "'"); strcat(text, str); strcat(text, "'"); // post condition: text has been extended by "'" + string + "'" void appendarray(char *text, vector *array) strcat(text, "["); VectorMap(array, appendpair, text); strcat(text, "]"); // post condition: text has been extended by "[" + array + "]" void appendobject(char *text, hashset *object) strcat(text, ""); HashSetMap(array, appendpair, text); strcat(text, ""); // post condition: text has been extended by "" + object + "" void appendpair(void *elemaddr, void *auxdata) char *text = auxdata; // rediscover 'master' buffer PythonPair *pair = elemaddr; if (pair->id!= NULL) appendstring(text, pair->id); strcat(text, ":"); switch (pair->type) case Integer: intcat(text, *(int *) pair->value); break; case Float: floatcat(text, *(float *) pair->value); break; case String: appendstring(text, *(char **) pair->value); break; case Array: appendarray(text, *(vector **) pair->value); break; case Object: appendobject(text, *(hashset **) pair->value); break; strcat(text, ","); void intcat(char *text, int i) intcpy(text + strlen(text), i); void floatcat(char *text, float f) floatcpy(text + strlen(text), f);

8 8 TA Notes Most students don t know about strcat, but they certainly should know strcpy. It s perfectly acceptable to me if that write code that computes the strlen every single time so it knows where in the text buffer it should continue strcpying. Some students threaded a struct through the code tree, where the struct contains the base address of the character buffer and the number of characters that have been written to it. That way they know where to continue writing characters. Several students didn t think to switch on the enumerated type, presumably because they didn t know it s backed by a scalar type. If you see cascaded if/else of tests like pair->type == String, that s fine, but note that a switch statement would make things a little cleaner. Don t worry about replication of code (they were feeling time pressure), and remark but don t penalize for missing commas and colons, since it s not exactly the focus of the problem, it easy to overlook, and once everything else worked it would be easy to debug it. Problem 3 Criteria: 15 points Proper string management is worth 7 points Sets aside the character buffer of the recommended size: 2 points (take off 1 if they dynamically allocate it and ultimately orphan it) Returning a string that s dynamically allocated, null-terminated, and is only as big as it needs to be to store the serialization: 2 points (take off 1 if they dynamically allocated the figure of size 8192 and returned that figure) Understands how to append text to the end of the running serialization (requires strcat, or combination of strcpy and strlen): 1 point Figures out how to append ints and floats, either using my intcpy and floatcpy inventions, or by using sprintf: 1point Mechanics of HashSetMap and VectorMap is worth 3 points Correctly threads buffer (or buffer/int pair) through as clientdata: 1 point Gets the prototype correct (void */void *) and properly reinterprets these void *s to be the data types they really are: 2 points (they lose both points if the prototypes are incorrect, and the lost just one point if they match the prototype but cast things incorrectly) Reinterpretations of the value fields are worth 3 points Properly casts value (=== &value[0]) when the value array is storing number data: 1 point Properly casts value to be a char ** and then dereferences it when the value array is storing a char *: 1 point Correctly casts value to be a container ** and then dereferences it: 1 point There are some dirtier ways to manage all this (like declaring a local variable of the required type and memcpy ing the material into it). As long as it works, I m fine with it. Slack points are capped at 2 points Use these two points to deduct for incorrect ampersanding (cap at 1 point), dotting instead of arrowing (cap at just 1 point), forgetting to print the id field, and so forth. Cap deductions here at 2 points.

CS107 Handout 26 Spring 2007 May 9, 2007 CS107 Midterm Exam

CS107 Handout 26 Spring 2007 May 9, 2007 CS107 Midterm Exam CS107 Handout 26 Spring 2007 May 9, 2007 CS107 Midterm Exam This is an open-note exam. You can refer to any course handouts, handwritten lecture notes, and printouts of any code relevant to a CS107 assignment.

More information

Spring 2008 May 14 th, 2008 CS107 Midterm Solution

Spring 2008 May 14 th, 2008 CS107 Midterm Solution CS107 Handout 25S Spring 2008 May 14 th, 2008 CS107 Midterm Solution Problem 1: Your Friendly Green Grocer (15 points: 5, 4, and 6) Consider the following struct definitions: line 1 line 2 line 3 typedef

More information

Kurt Schmidt. October 30, 2018

Kurt 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 information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

CS 222: Pointers and Manual Memory Management

CS 222: Pointers and Manual Memory Management CS 222: Pointers and Manual Memory Management Chris Kauffman Week 4-1 Logistics Reading Ch 8 (pointers) Review 6-7 as well Exam 1 Back Today Get it in class or during office hours later HW 3 due tonight

More information

Dynamic Allocation in C

Dynamic Allocation in C Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,

More information

For example, let s say we define an array of char of size six:

For example, let s say we define an array of char of size six: Arrays in C++ An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location, we specify the name and then the positive index into

More information

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Introduction to C++ with content from

Introduction to C++ with content from Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

A few examples are below. Checking your results in decimal is the easiest way to verify you ve got it correct.

A few examples are below. Checking your results in decimal is the easiest way to verify you ve got it correct. CS107 Handout 22S Spring 2007 May 4, 2007 Assignment 5 Solution Brought to you by Julie Zelenski and Jerry Cain. Problem 1: Binary numbers and bit operations A few examples are below. Checking your results

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

8*4 + 4 = 36 each int is 4 bytes

8*4 + 4 = 36 each int is 4 bytes CS 61CL (Clancy) Solutions and grading standards for exam 1 Spring 2009 169 students took the exam. The average score was 43.6; the median was 46. Scores ranged from 1 to 59. There were 89 scores between

More information

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

Heap Arrays and Linked Lists. Steven R. Bagley

Heap 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 information

Recitation #11 Malloc Lab. November 7th, 2017

Recitation #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 information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //

More information

CS 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 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 information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 11. Linked Lists. Mark Redekopp 1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. Name: ECE551 Midterm NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual work. You

More information

Dynamic Allocation in C

Dynamic Allocation in C Dynamic Allocation in C 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically, as the program

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016 Malloc Lab & Midterm Solutions Recitation 11: Tuesday: 11/08/2016 Malloc 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than

More information

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam Name: ECE 551D Spring 2018 Midterm Exam NetID: There are 6 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 11. Linked Lists. Mark Redekopp 1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++

More information

Introduction to C: Pointers

Introduction to C: Pointers Introduction to C: Pointers Nils Moschüring PhD Student (LMU) Nils Moschüring PhD Student (LMU), Introduction to C: Pointers 1 1 Introduction 2 Pointers Basics Useful: Function

More information

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

advanced 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 information

Heap Arrays. Steven R. Bagley

Heap 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 information

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming Procedural Programming & Fundamentals of Programming Lecture 3 - Summer Semester 2018 & Joachim Zumbrägel What we know so far... Data type serves to organize data (in the memory), its possible values,

More information

Instructor (Jerry Cain)

Instructor (Jerry Cain) ProgrammingParadigms-Lecture04 Instructor (Jerry Cain):Hey, hey everyone. Welcome. You made it through a week of 107. I have two handouts for you today, although I really only have one. I have one fresh

More information

HW1 due Monday by 9:30am Assignment online, submission details to come

HW1 due Monday by 9:30am Assignment online, submission details to come inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

This section provides some reminders and some terminology with which you might not be familiar.

This section provides some reminders and some terminology with which you might not be familiar. Chapter 3: Functions 3.1 Introduction The previous chapter assumed that all of your Bali code would be written inside a sole main function. But, as you have learned from previous programming courses, modularizing

More information

Pointers. Memory. void foo() { }//return

Pointers. Memory. void foo() { }//return Pointers Pointers Every location in memory has a unique number assigned to it called it s address A pointer is a variable that holds a memory address A pointer can be used to store an object or variable

More information

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 3 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2017 ENCM 339 Fall 2017 Section 01

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths

More information

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER: Page 1 of 7 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2014 Midterm Examination # 2 Wednesday, March 19, 2014 ANSWERS Duration of examination: 75 minutes STUDENT

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

CS 3L (Clancy) Solutions and grading standards for exam 1

CS 3L (Clancy) Solutions and grading standards for exam 1 CS 3L (Clancy) Solutions and grading standards for exam 1 Fall 2009 *** DRAFT 177 students took the exam. We are still gathering statistics about the exam (mean and median). However, were you to receive

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 220: Computer Systems & Programming Structured Data in C Sometimes, Knowing Which Thing is Enough In MP6, we

More information

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns What is an array? Pointers Memory issues The name of the array is actually a memory address. You can prove this by trying to print

More information

MPATE-GE 2618: C Programming for Music Technology. Syllabus

MPATE-GE 2618: C Programming for Music Technology. Syllabus MPATE-GE 2618: C Programming for Music Technology Instructor Dr. Schuyler Quackenbush schuyler.quackenbush@nyu.edu Lab Teaching Assistant TBD Description Syllabus MPATE-GE 2618: C Programming for Music

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 C Strings, Arrays, & Malloc 2007-06-27 Scott Beamer, Instructor Sun announces new supercomputer: Sun Constellation CS61C L3 C Pointers

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

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

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites: C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

CS50 Supersection (for those less comfortable)

CS50 Supersection (for those less comfortable) CS50 Supersection (for those less comfortable) Friday, September 8, 2017 3 4pm, Science Center C Maria Zlatkova, Doug Lloyd Today s Topics Setting up CS50 IDE Variables and Data Types Conditions Boolean

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

CS 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 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 information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 11: Bit fields, unions, pointers to functions Cristina Nita-Rotaru Lecture 11/ Fall 2013 1 Structures recap Holds multiple items as a unit Treated as scalar in C: can be

More information

CS 251 Intermediate Programming Java Basics

CS 251 Intermediate Programming Java Basics CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions

More information

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)! Reference slides! You ARE responsible for the material on these slides (they re just taken from the reading anyway). These were the slides that generated the fewest questions in years past (i.e., those

More information

WHAT POINTERS REALLY ARE

WHAT POINTERS REALLY ARE POINTERS What is a pointer? The index of a book contains pointers. A URL (e.g., http://turing.ubishops.ca/home/cs318) is a pointer. A street address is a pointer. What is then a forwarding address? a pointer

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory

More information

Instructor (Jerry Cain)

Instructor (Jerry Cain) ProgrammingParadigms-Lecture07 Instructor (Jerry Cain):Hey, everyone. Welcome. I have one handout for you today. It is Assignment 3. It is due next Thursday evening. You ll get Assignment 4 next Wednesday.

More information

Object-Oriented Programming

Object-Oriented Programming iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 Overview 1 2 3 4 5 6 7 I No beard, no belly, no guru... Ken Thompson (B), Dennis Ritchie (C) - UNIX Bjarne Stroustrup (C++) James Gosling (Java) Figure:

More information

CS 237 Meeting 19 10/24/12

CS 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 information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 C Pointers 2004-09-08 Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Cal flies over Air Force We re ranked 13 th in the US and

More information

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Agenda Pointers Arrays in C 2 Address vs. Value Consider

More information

CSC 1300 Exam 4 Comprehensive-ish and Structs

CSC 1300 Exam 4 Comprehensive-ish and Structs CSC 1300 Exam 4 Comprehensive-ish and Structs December 8, 2017 Name: Read through the entire test first BEFORE starting Multiple Choice and T/F sections should be completed on the scantron Test has two

More information

Lecture 9 Assertions and Error Handling CS240

Lecture 9 Assertions and Error Handling CS240 Lecture 9 Assertions and Error Handling CS240 The C preprocessor The C compiler performs Macro expansion and directive handling Preprocessing directive lines, including file inclusion and conditional compilation,

More information

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14 Reading Assignment Strings char identifier [ size ] ; char * identifier ; K.N. King Chapter 13 K.N. King Sections 23.4, 23.5 Supplementary reading Harbison & Steele Chapter 12, 13, 14 Strings are ultimately

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

In further discussion, the books make other kinds of distinction between high level languages:

In further discussion, the books make other kinds of distinction between high level languages: Max and Programming This essay looks at Max from the point of view of someone with a bit of experience in traditional computer programming. There are several questions that come up from time to time on

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Do not start the test until instructed to do so!

Do not start the test until instructed to do so! Instructions: Print your name in the space provided below. This examination is closed book and closed notes, aside from the permitted one-page formula sheet. No calculators or other electronic devices

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

1d: tests knowing about bitwise fields and union/struct differences.

1d: tests knowing about bitwise fields and union/struct differences. Question 1 1a: char ptr[] = Hello World ; char a = ptr[1], b = *(ptr+6); Creates an array of 12 elements, 11 visible letters and a character value 0 at the end. i true ii true iii false iv false v true

More information

CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II

CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II Example: Simple variables Handout written by Julie Zelenski and Nick Parlante A variable is a location in memory. When a variable

More information

Quiz 0 Review Session. October 13th, 2014

Quiz 0 Review Session. October 13th, 2014 Quiz 0 Review Session October 13th, 2014 Topics (non-exhaustive) Binary. ASCII. Algorithms. Pseudocode. Source code. Compiler. Object code. Scratch. Statements. Boolean expressions. Conditions. Loops.

More information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 8: Dynamically Allocated Linked Lists 2017-2018 Fall int x; x = 8; int A[4]; An array is stored as one contiguous block of memory. How can we add a fifth element to the

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

CSC231 C Tutorial Fall 2018 Introduction to C

CSC231 C Tutorial Fall 2018 Introduction to C mith College CSC231 C Tutorial Fall 2018 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 4 Installments! Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to Assembly Unix Standard

More information

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Structs & Memory Management 9/5/2007 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Structs (1) C String Standard Functions

More information

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September CS 1313 010: Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September 19 2018 This second assignment will introduce you to designing, developing, testing

More information

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = "abc";! How do you tell how long a string is?!

Reference slides! C Strings! A string in C is just an array of characters.!!!char string[] = abc;! How do you tell how long a string is?! CS61C L04 Introduction to C (pt 2) (1)! Reference slides! C Strings! You ARE responsible for the material on these slides (they re just taken from the reading anyway). These were the slides that generated

More information

Important Questions for Viva CPU

Important Questions for Viva CPU Important Questions for Viva CPU 1. List various components of a computer system. i. Input Unit ii. Output Unit iii. Central processing unit (Control Unit + Arithmetic and Logical Unit) iv. Storage Unit

More information

CS 61c: Great Ideas in Computer Architecture

CS 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 information

My malloc: mylloc and mhysa. Johan Montelius HT2016

My malloc: mylloc and mhysa. Johan Montelius HT2016 1 Introduction My malloc: mylloc and mhysa Johan Montelius HT2016 So this is an experiment where we will implement our own malloc. We will not implement the world s fastest allocator, but it will work

More information

C++ for Java Programmers

C++ 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 information