I hope you: - PowerPoint PPT Presentation

1 / 32
About This Presentation
Title:

I hope you:

Description:

I hope you: – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 33
Provided by: jack195
Category:
Tags: collection | hope

less

Transcript and Presenter's Notes

Title: I hope you:


1
CS110 Lecture 23 Object Oriented Programming
Misc. Lost Details
Jack Tumblinjet_at_cs.northwestern.edu
  • I hope you
  • Have completed PA-4, due today
  • Used Blackboard to turn in PA-4
  • Have started on Project 5, DUE WED. DEC 3
  • Know all about structures pointers Chap.
    12 except 12-8

2
Question from TAs
  • Infinite loops what happens if you do this?
    eventually?
  • int main()
  • int i
  • for(i 0 i gt -1 i)
  • // do something useful...
  • return 0

3
Question from TAs
Variable i keeps growing the set of integers
isn't infinite only holds numbers from -231 to
231. when i reaches 231, then i will produce
i -231, AND THEN THE LOOP STOPS!
  • Infinite loops what happens if you do this?
    eventually?
  • int main()
  • int i
  • for(i 0 i gt -1 i)
  • // do something useful...
  • return 0

4
NEW! Blackboard turn-in
  • For project 4 and 5, use 'Digital Drop Box'
    Blackboard Tools button, Digital
    Drop Box, Add File, then Send File
  • Be sure to SEND, don't just ADD FILE We don't
    receive your file until you hit 'send'!
  • No need to turn in paper printouts

5
Collections of Objects (C)(May help on
Project 5)
  • A Game uses a bunch of somethings
  • Several different classes (robots, trees,
    clouds, castles, dogs, cats,...)
  • Each with different actions abilities
    blink(), armsUp(), armsDown(), sleep(), walk(),
    run(),
  • May want to create/destroy objects as game
    progresses
  • How can we do that? first ask
  • How can we store them?
  • Hint think about a changing collection of
    objects as a changing collection of struct
    variables.

6
Collections of Objects(May help on Project 5)
  • Idea 0 Declare sets of individually named struct
    variables for every possible object your program
    will ever need
  • fishT oneFish, twoFish, redFish, blueFish
  • carT carGo, carPet, carToon, carTell
  • lokT lokNess, iwazLok, shewasLok, swanLok
  • All have complete member variables that
    describe absolutely everything that can change
    'name', 'isAlive', 'age', 'position',
    'isHungry', isDry', 'energy'...
  • Idea 1 Fixed Arrays of struct variables an
    array of fishT objects, an array of carT, an
    array of lokT. Tedious, inflexible, fixed cant
    easily create, destroy, swap, rearrange...
  • Idea 2 Dynamically-Alloc'd Arrays of struct
    variables make a pointer-to-fishT, a
    pointer-to-carT, a pointer-to-lokT, then reserve
    memory for the array...

7
Collections of Objects(useful, but not
included in Project 5)
  • Idea 3 Make a new struct to point to any ONE
    thing(optional not needed for Project 5)
  • typedef struct holderT int kindOf / if
    kindOf0, we are EMPTY /
  • fishT pF / if kindOf1, point to a
    fishT / carT pC / if kindOf2,
    point to a carT / lokT pL / if
    kindOf3, point to a lokT /
  • holderT
  • The 'kindOf' member variable tells you which
    pointer (pF, pC, pL, or none) to use. All the
    other pointers are kept NULL.

8
Collections of Objects
typedef struct holderT int kindOf / if
kind0, we are EMPTY! / fishT pF
/ if kind1, points to a fishT / carT
pC / if kind2, points to a carT /
lokT pL / if kind3, points to a lokT
/ holderT
  • Idea 3 (cont'd)
  • Create an object? set the value for kindOf,
    then malloc()an object for the selected pointer
  • holderT myn
  • ...myn.kindOf 2 / We will hold a carT
    object /myn.pC (carT )malloc(1
    sizeof(carT))myn.pF NULL myn.pL NULL
  • Destroy an object? use kindof to find its
    pointer call free() ...
  • Access an object? Lets try it.... assume a 'carT'
    object. Write code to print its floating-point
    member 'x_vel' ...

9
Data Nesting
  • Many forms of data are naturally nested USE
    THIS!
  • Universe?SolarSystem?planet?continent?country?stat
    e/province?town?precinct?street?building?room?chai
    r
  • Matrix?row?element
  • Movie?frame?scanline?pixel?color
  • Least restrictive, clearest data nesting tool
    Structures
  • Nested Structures members are other structure
    types
  • allows separate struct name for each nesting
    level cityT( street,road,hiway
    members)?streetT(house,building members),?
    houseT(yard,room,hall members),?roomT(door,window,
    furnit. members)? furnitureT(desk,chair,bed
    members),?deskT(drawer,leg,top,side...)?
  • Wonderful Structures can use arrays as members
    (fixed or dynamic allocd)

10
Collections of Objects (C)(May help on
Project 5)
  • We humans tend to organize our world as
    collections of objects
  • We give names to classes of objects (or kinds
    of objects) birds, clouds, trees, people,
    triangles, books, animals, buildings, chairs,
    tables, etc.
  • Each kind of object has many variable parts
    name, address, salary, dept, office, SS,
    supervisor, etc.
  • An object is just one named, countable,
    discrete object Bob Cratchit, emp1,
    newest_hire, etc.
  • Each class of object has many associated actions
    hire, fire, demote, promote, retire, re-assign,
    work overtime, travel, vacation, training, move
    to new city, ...

11
Collections of Objects (C)(May help on
Project 5)
  • Our best strategy in C Organize the entire
    program as a collection of objects
  • A class of object data structure type we
    define and name
  • its member variables define each part of the
    object,
  • One (data-structure-type) variable one
    countable object
  • Each class of object has its own set of related
    functions wagonInit(), wagonDraw(),
    wagonMove(), etc.

12
Collections of Objects (C)
  • The strategy known as "Object-Oriented
    Programming" (C, Java, Modula,
    Smalltalk,...) Organize the entire program as a
    collection of objects
  • A class of object data structure type we
    define and name
  • its member variables define each part of the
    object,
  • One (data-structure-type) variable one
    countable object
  • Each class of object has its own set of member
    functions wagon.Init(), wagon.Draw(),
    wagon.Move(), etc.
  • In C, 'class' ( a struct its 'member'
    functions )

13
Collections of Objects (C)
  • Key idea of object oriented programming
  • Object data structure all its related
    functions
  • Use nesting of classes to keep things simple
  • cityT ? streetT ? houseT ? roomT ? chairT...
  • Writing cityT functions? Please don't make me
    worry about the number of chairs in each room!.

14
Misc. Lost Details
  • Congratulations!
  • You now know all the essentials of C
  • You're ready for C
  • You're ready to learn a few key algorithms
  • There are a few leftover details to clean up
    first

15
"Hey! I can even point to myself!"
a data structure
  • Data structure members can be (almost) any type,
    including
  • all basic types int, char, float, double
  • all derived types enum, arrays, pointers,
    structures
  • even a pointer to our own kind of struct! if
    you're careful but not
    array of our own kind of struct (do you know
    why?)
  • typedef struct employeeT/employee record
    /
  • char name / string variable /int
    IDnum / employee ID /float salary / in
    dollars /char ssn11 / xxx-xx-xxxx /stru
    ct employeeT pBoss / immediate
    supervisor /struct employeeT pPeon / team
    member /
  • employeeT

16
Self-pointing is tricky...
  • Data structure members can be (almost) any type,
    including
  • even a pointer to our own kind of struct!
  • SURPRISE! THIS SYNTAX DOESNT WORK!
  • typedef struct employeeT /employee record
    /
  • char name / string constant /int
    IDnum / employee ID /float salary / in
    dollars /char ssn11 / xxx-xx-xxxx /empl
    oyeeT pBoss / immediate supervisor /employeeT
    pPeon / team member /
  • employeeT

17
Self-pointing is tricky...
  • Instead, you must do this
  • typedef struct employeeT /employee record
    /
  • char name / string constant /int
    IDnum / employee ID /float salary / in
    dollars /char ssn11 / xxx-xx-xxxx /str
    uct employeeT pBoss / immediate
    supervisor /struct employeeT pPeon / team
    member /
  • employeeT
  • ?HUNH? WHAT HAPPENED HERE?
  • actual datatype is struct employeeT, but
    typedef renames datatype to employeeT
  • These lines are compiled before typedef can do
    the renaming,so they must use the actual
    datatype name struct employee

18
scanf() more of the story
(CHAPTER 11-6 IN BOOK look at 11-5 too!)
  • int scanf(format string, ptr1, ptr2, ptr3, )
  • Format String
  • Can set max of chars for each data conversion
  • Can set separators (besides whitespace)
  • cnt scanf(3i, 80s,my_int, msg)
  • Return value of successful conversions (or 1
    if nothing at all matches)
  • Destinations are ALL pointers/array names.

19
scanf() more of the story
(CHAPTER 11-6 IN BOOK look at 11-5 too!)
  • int scanf(format string, ptr1, ptr2, ptr3, )
  • Format String
  • Can set max of chars for each data conversion
  • Can set separators (besides whitespace)
  • cnt scanf(3i, 80s,my_int, msg)
  • Return value of successful conversions (or 1
    if nothing at all matches)
  • Destinations are ALL pointers/array names.

20
scanf() more of the story
(CHAPTER 11-6 IN BOOK look at 11-5 too!)
  • int scanf(format string, ptr1, ptr2, ptr3, )
  • Format String
  • Can set max of chars for each data conversion
  • Can set separators (besides whitespace)
  • cnt scanf(3i, 80s,my_int, msg)
  • Return value of successful conversions (or 1
    if nothing at all matches)
  • Destinations are ALL pointers/array names.

21
scanf() more of the story
(CHAPTER 11-6 IN BOOK look at 11-5 too!)
  • int scanf(format string, ptr1, ptr2, ptr3, )
  • Format String
  • Can set max of chars for each data conversion
  • Can set separators (besides whitespace)
  • cnt scanf(3i, 80s,my_int, msg)
  • Return value of successful conversions (or 1
    if nothing at all matches)
  • Destinations are ALL pointers/array names.

22
scanf() more of the story
(CHAPTER 11-6 IN BOOK look at 11-5 too!!)
  • int scanf(format string, ptr1, ptr2, ptr3, )
  • Format String
  • Can set max of chars for each data conversion
  • Can set separators (besides whitespace)
  • To read an entire line (up to 80 chars) of text
    as a string, replace 80s with 80\n (note
    no s)
  • cnt scanf(3i, 80\n,my_int, msg)

read a string, but dont stop until you read 80
chars or find a \n
23
Format Strings Can be Variable!
  • So far, weve used only string constantsscanf(
    d,val)printf(Value is d\n,val)
  • But we can use string variables too(recall
    'string' variable? use a pointer or array name)
  • char inMsg10 dchar outMsg20
    Value is d\n... scanf(inMsg,val)
    printf(outMsg,val)

24
(Recall) Literals
  • Numerical literals in C are obviousint i
    float base_e i3 base_e
    2.718281828OR, more compactlyint i 3
    float base_e 2.718281828These literals set
    the values for i, base_e, and are not
    L-valuesthey do not have an address. pV 3
    pF 2.71828 3 pF

ERROR!!
25
String Literals?
  • String Literals in C are a little strange
    they ARE L-values, they DO have address char
    pMsg...
  • pMsg Are we having fun yet?
  • OR, more compactlychar pMsg Are we having
    fun yet?
  • Pointer pMsg gets the address of a string
    literal. Literal's chars are in 'locked'
    memory--const.ERROR if you try to change its
    contents!
  • strcpy(Real Soon now!,pSrc)

String literal
ERROR!!
26
String Constants
  • Reminder Arrays arent movable!
  • We can move a pointer pMsg to a string literals
    addresschar pMsg
  • pMsg Are we having fun yet? // OK!
  • And we can initialize an array msg by copying a
    string literalchar msg20 Are we having
    fun yet? // OK!
  • But we cant move an array name msg to that
    locationchar msg20
  • msg Not this way, no! // ERROR!

address
all chars
27
Build a String sprintf()
  • int sprintf( pStr, format_string, arg0, arg1,
    )
  • Think string printf it constructs a formatted,
    printable string of chars in memory, starting at
    location pStr.
  • Arguments pStr char. pointer to showing where
    to write string
  • format_string (same as used in printf)
  • arg0, arg1, list of values used in format
    string
  • Return value number of non-null chars written
    to pStrWARNING!! Reserve a block of memory at
    pStr first!

28
More about string.h
  • Uses Char Pointer arguments and return types
    (pass-by-reference)
  • YOU must ensure enough memory was reserved for
    all operations of all string.h functions!
  • All have form str(n)xxx (dest, src, n), and
    include length strlen, copy
    strcpy, compare strcmp, concatenate strcat,
    find char strchr, find string strstr.
  • Other, more obscure string.h functions strerror(
    ), strpbrk(), strtok(), strcspn(), strspn(),

MAJOR source of subtle bugs!
29
Jargon Buffer
  • Buffer temporary storage for a data sequence
  • A pointer is not a buffer until it points to a
    reserved block of memory
  • Reserved by dynamic allocation (malloc,free) or
  • Reserved by a declared array (still in scope, or
    static)
  • CAUTION never over-run a buffermake sure all
    string lengths lt buffer length
  • HELPFUL All string.h functions have an n
    version strncpy, strncmp, strncat, strnchr
    operates on only the first n characters

30
Subtlety of strncpy, strncat
  • char strncpy(char dest, char src, int n)
  • Always copies n chars to dest. Of these, it
  • Copies src chars until null \0 char found,
    then
  • Copies additional null chars after that.
  • CAREFUL! If src longer than n, NO null char!!
  • char strncat(char dest, char src, int n)
  • Appends no more than n chars from src onto dest
  • CAREFUL! If src longer than n, NO null char!!

31
Other useful string.h functions
  • int strncmp(char str1, char str2, int n)
  • Compares first n characters of strings 1 2
  • Returns the DIFFERENCES 0 perfect match!
  • char strchr(char str, char ch)
  • Searches string str for the 1st char ch it
    finds,
  • Returns pointer to the char it found, or NULL
  • char strstr(char str, char ch)
  • Searches string str1 for the 1st string str2
    it finds,
  • Returns pointer to the string it found, or NULL.

32
Finish up
  • Worthwhile topics
  • Search, Sort Chapter 8-5
  • Chap 14 Linked lists
  • Intro to C
  • Skipped so far
  • Chapter 13-1,2 Binary files,
  • Chapters 13-4 fgets/getssscanf,
    fputs/putssprintf
  • Chap 15 Bitwise operators, bit-shift
  • Appendix G pre-proc directives include
  • Appendix I command-line arguments
  • Appendix J Function pointers
Write a Comment
User Comments (0)
About PowerShow.com