CS 222: Arrays, Strings, Structs

Similar documents
CS 222: Control Flow (Conditionals and Iteration)

CS 222: Pointers and Manual Memory Management

CS 222: More File I/O, Bits, Masks, Finite State Problems

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS 222: Linked Lists, Queues, Stacks

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Types II. Hwansoo Han

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

Wednesday, October 15, 14. Functions

Class Information ANNOUCEMENTS

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

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

CS 211: Methods, Memory, Equality

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

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

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CS558 Programming Languages

Topics Introduction to Microprocessors

Introduction to C++ with content from

Character Strings. String-copy Example

CS 310: ArrayList Implementation

Kurt Schmidt. October 30, 2018

CS61, Fall 2012 Section 2 Notes

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Lab 4: Tracery Recursion in C with Linked Lists

CS 61c: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Welcome to... CS113: Introduction to C

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

ECE 15B COMPUTER ORGANIZATION

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

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

CSE 333 Midterm Exam 5/10/13

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

CS 61C: Great Ideas in Computer Architecture Introduction to C

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Advanced Systems Programming

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Arrays and Pointers in C & C++

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Weeks 6&7: Procedures and Parameter Passing

COMP-520 GoLite Tutorial

Pointers and References

Pointers in C/C++ 1 Memory Addresses 2

The role of semantic analysis in a compiler

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

CSCI 2021: Introduction

CS113: Lecture 4. Topics: Functions. Function Activation Records

First of all, it is a variable, just like other variables you studied

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

Memory and Pointers written by Cathy Saxton

Common Misunderstandings from Exam 1 Material

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

CS 222: Overview of C

CS 314 Principles of Programming Languages. Lecture 11

Programming refresher and intro to C programming

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 100: Computability, Python Lists

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

Heap Arrays. Steven R. Bagley

CS61C : Machine Structures

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

CS61C Midterm Review on C & Memory Management

Review of the C Programming Language for Principles of Operating Systems

Dynamic Data Structures. CSCI 112: Programming in C

CS24 Week 2 Lecture 1

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

AIMS Embedded Systems Programming MT 2017

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS61C : Machine Structures

CS 137 Part 2. Loops, Functions, Recursion, Arrays. September 22nd, 2017

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Week 7 Part I. Kyle Dewey. Monday, August 6, 12

a data type is Types

Chapter 1 Getting Started

CS 2113 Software Engineering

CSE 333 Midterm Exam 7/29/13

ECEN 449 Microprocessor System Design. Review of C Programming

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

Goals of this Lecture

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

CA31-1K DIS. Pointers. TA: You Lu

Page 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics

CS 110 Computer Architecture. Lecture 2: Introduction to C, Part I. Instructor: Sören Schwertfeger.

Intermediate Programming, Spring 2017*

CS Lecture #14

Transcription:

CS 222: Arrays, Strings, Structs Chris Kauffman Week 3-1

Logistics Reading Ch 6 (arrays) Ch 7 (structs) HW 2 & 3 HW 2 due tonight Conditionals, loops, arrays, natural log HW 3 up tomorrow, due next week Exam 1 This Thursday Zyante Ch 1-6 This week s Material Included Exam Practice Post problems tomorrow morning

Goals HW 2 Questions Arrays

HW 2 Questions Any to discuss?

Data Types Define Now there s a type, it looks like blah Declare Here is a variable, it s type is bleh Access Element foo of variable bar has value... Assign Element foo of variable bar gets value blip

Scalar Types Only one element/value per variable Define Done for you for int,double,char etc Declare?? Access?? Assign??

Aggregate Data: Two Kinds Arrays collection of the same thing (homogeneous) Like vectors/matrices Indexed by number Elements accessed via array[index] structs collection of different things (heterogeneous) A record Named elements (field) Elements accessed via mystruct.fieldname

Arrays A block of memory Define Built in Declare type name[size]; Access x = name[index]; Alter name[index] = x; See arraytypes.c

Initialize Initial values are undefined - gabbledegook Must initialize values, typically By hand By loop Immediate notation: {el1, el2, el3} By library call (later) See array_init.c

Exercise: Price is Right int guesses[] = {45, 22, 86, 37, 12, 13, 47}; int find_closest_guess(int actual_price){... } Use a set of loops and conditionals to determine the closest value in guesses to actual_price that does not go over actual_price. Return the closest value from the function If all values in guesses are larger than actual_price, return -1 lila [w02-2-code]% gcc price_right.c lila [w02-2-code]% a.out Guesses: 45 22 86 37 12 13 47 Actual 42 closest_guess 37 Actual 46 closest_guess 45 Actual 22 closest_guess 22 Actual 10 closest_guess -1

Arrays as Function Arguments Definitely can pass arrays as arguments void print_doubs(double d[], int len){ int i; for(i=0; i<len; i++){ printf("%2d: %lf\n",i,d[i]); } printf("\n"); } int main(){ double my_doubs[] = {1.23, 4.56, 37.89, 3.21}; print_doubs(my_doubs, 4); } /* VERY COMMON ERROR: don t use [] when passing */ print_doubs(my_doubs[], 4); return 0;

Exercise Define int occurrences(int a[], int length, int key) a an array of ints length number of elements in a key what to look for in a returns how many times key occurs in a int stuff[8] = {-2, 1, 1, 0, -1, 1, 0, 2}; int zeros = occurrences(stuff, 8, 0); /* 2 */ int ones = occurrences(stuff, 8, 1); /* 3 */ int tens = occurrences(stuff, 8, 10); /* 0 */

Arrays as Multiple Returns Definitely can set array values; changes in the caller void change_doubs(double d[], int len){ int i; for(i=0; i<len; i++){ d[i] = len-i; } printf("\n"); } int main(){ double my_doubs[] = {1.23, 4.56, 37.89, 3.21}; change_doubs(my_doubs, 4); printf("%lf\n",my_doubs[1]); } Does this work for scalar int, double, char arguments?

Arrays as Function Returns Definitely cannot return arrays from functions /* Error! */ int [] someints(){ int x[3] = {1,2,3}; return x; } Try compiling arrayreturn.c Overcome this limitation next week

Arrays and the Stack: Be Careful Uninitialized stack memory could be anything See random_initialize.c

Common Misconceptions Arrays have a length but it is NOT stored anywhere implicitly Must use a local variable or constant to track length No way to ask what the length of an array is sizeof() DOES NOT do this

BREAKTIME Back in 15 minutes

Goals Exam 1 Rules struct

Open Resource Exam Rules Exam 1 time: 1 Hours and 15 Minutes Can Use, physical or electronic Notes Textbook(s) (online ok) Editor Compiler IDE Authorized Docs Locally stored webpages Dictionary Notes Silence your devices Cannot Use Keep device screens visible to instructor If you aren t sure of something, ask General Internet Search Piazza/Discussion Board Chat/Texting Communication with anyone but Instructor/Proctor

An Instructive Example Zyante: Iterating through an array example: Program that finds the max item. In w03-1-code/read_arrays_zyante.c This example is interesting for several reasons User input into an array scanf("%d", &(a[i])); Iteration converts 1-indexed loop to 0-indexed arrays Finds max element (best element, useful for HW) Stack allocated array based on local variable N Contrast this with

struct: Heterogeneous Data A block of memory with named fields Define typdef struct {...} name_t; Declare name_t var; Access x = var.fieldname; Alter var.fieldname = x; See modernstruct.c

Declare struct There now exists a data type that looks like.... Important: Several syntax variants Modern typdef struct {...} name; newstruct.c Zyante typdef struct name_struct {...} name; newstruct.c Old-school struct name {...}; oldstruct.c One-off struct {...} var; weirdstruct.c OMG struct name {...}; typedef struct name name_t;

Define: We ll favor modern typedef struct { double x, y; char color; int shape; } point_t; Warning: standard libraries use Textbook and Old-school styles

Assigning Aggregate Data Cannot assign whole arrays to one another Can assign whole structs to one another See aggregate_assign.c Related Cannot return an array from a function 1 Can return a struct from a function 1 You can return a pointer to an array, we ll do this later; you can return a pointer to a fixed size array but the syntax is an abomination

struct As Function Args and Return Values Both are readily done: colors.c /* A simple struct for an RGB color */ typedef struct { double red; double green; double blue; } color_t;

Returning an int vs struct typedef struct { int a; double b;} mystruct; Return an int // return an int like this int get_int(){ int a = 22; return a; } // NOT like this int get_int(){ int a = 22; return int; } // and NOT like this int get_int(){ int a = 22; return int a; } Return a struct // return a struct like this mystruct get_struct(){ mystruct s = {.a=1, b=2.3 }; return s; } // NOT like this mystruct get_struct(){ mystruct s = {.a=1,.b=2.3 }; return mystruct; } // and NOT like this mystruct get_struct(){ mystruct s = {.a=1, b=2.3 }; return mystruct s; }

Exercise Write a function bluer Takes two color_ structs Determines which struct has a higher blue field Returns that struct /* A simple struct for an RGB color */ typedef struct { double red; double green; double blue; } color_t; int main(){ color_t c1 = {.red=0.5,.green=0.7,.blue=0.1}; color_t c2 = {.red=0.6,.green=0.2,.blue=0.5}; } color_t r = bluer(c1,c2); /* should be same as c2 now */

Aggregate Data Gotchyas Arrays Cannot assign whole arrays to one another Cannot return an array from a function 2 structs Can assign whole structs to one another Can return a struct from a function See aggregate_assign.c 2 You can return a pointer to an array, we ll do this later; you can return a pointer to a fixed size array but the syntax is an abomination

Sharing Types Can copy/paste struct definitions in every.c file that needs it Lots of code... 1 change breaks everything Instead, put planet_t in "planet.h" #include "planet.h" Includes definitions in the right places

Composing Elements See solarsys.c A struct with an array typedef struct{ char name[128]; double dist; } planet_t;... { planet_t earth = {"earth", 1.0}; } An array of structs planet_t solarsys[9]; double d5 = solarsys[5].dist; Later, structs with structs as elements

Code Vs Data In solarsys.c we have a nice way to express the layout of some data in code. This doesn t happen very often in C, C++, Java, etc. It happens a lot in Lisp, ML, Haskell, Python, etc.

So far Comments Statements/Expressions Variable Types Assignment Basic Input/Output Function Declarations Conditionals (if-else) Iteration (loops) Aggregate data (arrays, structs, objects, etc) Library System Are we done?