Sei sulla pagina 1di 49

Learn C The Hard Way A Clear & Direct Introduction To Modern C Programming

Zed A. Shaw July 2011


Contents Preface Introduction: The Cartesian Dream Of C What You Will Learn How To Read This Book The ore o!"eten#ies Li#ense

I Basic Skills
1 Exercise 0: The Setup 1.1 Linu$ 1.2 %a# &S' 1.( Windows 1.) Te$t *ditor Exercise 1: Dust Off That Compiler 2.1 What You Should See 2.2 How To Break +t 2.( *$tra redit ! Exercise : "ake Is #our P$thon %o& (.1 ,sin- %ake (.2 What You Should See (.( How To Break +t (.) *$tra redit ' Exercise !: (ormatted Printin) ).1 What You Should See ).2 *$ternal Resear#h

).( How To Break +t ).) *$tra redit * Exercise ': Introducin) +al)rind ..1 +nstallin- /al-rind ..2 ,sin- /al-rind ..( What You Should See ..) *$tra redit , Exercise *: The Structure Of - C Pro)ram 0.1 What You Should See 0.2 Breakin- +t 1own 0.( *$tra redit . Exercise ,: T$pes Of +aria/les 2.1 What You Should See 2.2 How To Break +t 2.( *$tra redit 0 Exercise .: "ore +aria/les1 Some "ath 3.1 What You Should See 3.2 How To Break +t 3.( *$tra redit 2 Exercise 0: Si3es -nd -rra$s 4.1 What You Should See 4.2 How To Break +t 4.( *$tra redit 10 Exercise 2: -rra$s -nd Strin)s 10.1 What You Should See 10.2 How To Break +t 10.( *$tra redit 11 Exercise 10: -rra$s Of Strin)s1 4oopin) 11.1 What You Should See 11.2 How To Break +t 11.( *$tra redit 1 Exercise 11: 5hile64oop -nd Boolean Expressions 12.1 What You Should See

12.2 How To Break +t 12.( *$tra redit 1! Exercise 1 : If1 Else6If1 Else 1(.1 What You Should See 1(.2 How To Break +t 1(.( *$tra redit 1' Exercise 1!: S&itch Statement 1).1 What You Should See 1).2 How To Break +t 1).( *$tra redit 1* Exercise 1': 5ritin) -nd 7sin) (unctions 1..1 What You Should See 1..2 How To Break +t 1..( *$tra redit 1, Exercise 1*: Pointers Dreaded Pointers 10.1 What You Should See 10.2 *$"lainin- 5ointers 10.( 5ra#ti#al 5ointer ,sa-e 10.) The 5ointer Le$i#on 10.. 5ointers Are 6ot Arrays 10.0 How To Break +t 10.2 *$tra redit 1. Exercise 1,: Structs -nd Pointers To Them 12.1 What You Should See 12.2 *$"lainin- Stru#tures 12.( How To Break +t 12.) *$tra redit 10 Exercise 1.: 8eap -nd Stack "emor$ -llocation 13.1 What You Should See 13.2 Hea" 7s. Sta#k Allo#ation 13.( How To Break +t 13.) *$tra redit 12 Exercise 10: Pointers To (unctions

14.1 What You Should See 14.2 How To Break +t 14.( *$tra redit 0 Exercise 12: - Simple O/9ect S$stem 20.1 How The 55 Works 20.2 The 5rototy"e &89e#t Syste! 20.( The :a!e +!"le!entation 20.) What You Should See 20.. Auditin- The :a!e 20.0 *$tra redit 1 Exercise 0: :ed;s -&esome De/u) "acros 21.1 The *rror Handlin- 5ro8le! 21.2 The 1e8u- %a#ros 21.( ,sin- d8-.h 21.) What You Should See 21.. How The 55 *$"ands %a#ros 21.0 *$tra redit Exercise 1: -d<anced Data T$pes -nd (lo& Control 22.1 A7aila8le 1ata Ty"es 22.2 A7aila8le &"erators 22.( A7aila8le ontrol Stru#tures ! Exercise : The Stack1 Scope1 -nd =lo/als 2(.1 What You Should See 2(.2 S#o"e; Sta#k; And Bu-s 2(.( How To Break +t 2(.) *$tra redit ' Exercise !: "eet Duff;s De<ice 2).1 What You Should See 2).2 Sol7in- The 5u<<le 2).( *$tra redit * Exercise ': Input1 Output1 (iles 2..1 What You Should See 2..2 How To Break +t

2..( The +=& >un#tions 2..) *$tra redit , Exercise *: +aria/le -r)ument (unctions 20.1 What You Should See 20.2 How To Break +t 20.( *$tra redit . Exercise ,: 5rite - (irst >eal Pro)ram 22.1 What +s devpkg? 22.2 5ro9e#t Layout 22.( The %ake@ile 22.) The Sour#e >iles 22.. The %idATer! *$a!

II Data Structures -nd -l)orithms


0 Exercise .: Creati<e -nd Defensi<e Pro)rammin) 23.1 The reati7e 5ro-ra!!er %indset 23.2 The 1e@ensi7e 5ro-ra!!er %indset 23.( The *i-ht 1e@ensi7e 5ro-ra!!er Strate-ies 23.) A""lyin- The *i-ht Strate-ies 23.. &rder +s 6ot +!"ortant 23.0 *$tra redit 2 Exercise 0: Intermediate "akefiles 24.1 The Basi# 5ro9e#t Stru#ture 24.2 %ake@ile 24.( What You Should See 24.) *$tra redit !0 Exercise 2: 4i/raries -nd 4inkin) (0.1 What You Should See (0.2 How To Break +t (0.( *$tra redit !1 Exercise !0: -utomated Testin) (1.1 Wirin- ," The Test >ra!ework (1.2 *$tra redit ! Exercise !1: De/u))in) Code

(2.1 1e8u- 5rintin- /s. :1B /s. /al-rind (2.2 A 1e8u--in- Strate-y (2.( ,sin- :1B (2.) 5ro#ess Atta#hin(2.. :1B Tri#ks (2.0 *$tra redit !! Exercise ! : Dou/le 4inked 4ists ((.1 What Are 1ata Stru#tures ((.2 %akin- The Li8rary ((.( 1ou8le Linked Lists ((.) Tests ((.. What You Should See ((.0 How To +!"ro7e +t ((.2 *$tra redit !' Exercise !!: 4inked 4ist -l)orithms ().1 What You Should See ().2 How To +!"ro7e +t ().( *$tra redit !* Exercise !': D$namic -rra$ (..1 Ad7anta-es And 1isad7anta-es (..2 How To +!"ro7e +t (..( *$tra redit !, Exercise !*: Sortin) -nd Searchin) (0.1 Radi$ Sort And Binary Sear#h (0.2 How To +!"ro7e +t (0.( *$tra redit !. Exercise !,: Safer Strin)s (2.1 Why Strin-s Were A Horri8le +dea (2.2 ,sin- 8strli8 (2.( Learnin- The Li8rary !0 Exercise !.: 8ashmaps (3.1 How To +!"ro7e +t (3.2 *$tra redit

!2 Exercise !0: 8ashmap -l)orithms (4.1 What You Should See (4.2 How To Break +t (4.( *$tra redit '0 Exercise !2: Strin) -l)orithms )0.1 What You Should See )0.2 Analy<in- The Results )0.( *$tra redit '1 Exercise '0: Binar$ Search Trees )1.1 How To +!"ro7e +t )1.2 *$tra redit ' Exercise '1: 7sin) Cache)rind -nd Call)rind (or Performance Tunin) )2.1 Runnin- all-rind )2.2 all-rind Annotatin- Sour#e )2.( Analy<in- %e!ory A##ess With a#he-rind )2.) Judo Tunin)2.. ,sin- B a#he-rind )2.0 *$tra redit '! Exercise ' : Stacks and ?ueues )(.1 What You Should See )(.2 How To +!"ro7e +t )(.( *$tra redit '' Exercise '!: - Simple Statistics En)ine )).1 Rollin- Standard 1e7iation And %ean )).2 +!"le!ention )).( How To ,se +t )).) *$tra redit '* Exercise '': >in) Buffer )..1 The ,nit Test )..2 What You Should See )..( How To +!"ro7e +t )..) *$tra redit

', Exercise '*: - Simple TCP@IP Client )0.1 Au-!ent The %ake@ile )0.2 The net#lient ode )0.( What You Should See )0.) How To Break +t )0.. *$tra redit '. Exercise ',: Ternar$ Search Tree )2.1 Ad7anta-es And 1isad7anta-es )2.2 How To +!"ro7e +t )2.( *$tra redit '0 Exercise '.: - (ast 7>4 >outer )3.1 What You Should See )3.2 How To +!"ro7e +t )3.( *$tra redit '2 Exercise '0: - Tin$ +irtual "achine Part 1 )4.1 What You Should See )4.2 How To Break +t )4.( *$tra redit *0 Exercise '0: - Tin$ +irtual "achine Part .0.1 What You Should See .0.2 How To Break +t .0.( *$tra redit *1 Exercise *0: - Tin$ +irtual "achine Part ! .1.1 What You Should See .1.2 How To Break +t .1.( *$tra redit * Exercise *1: - Tin$ +irtual "achine Part ' .2.1 What You Should See .2.2 How To Break +t .2.( *$tra redit *! Exercise * : - Tin$ +irtual "achine Part * .(.1 What You Should See .(.2 How To Break +t

.(.( *$tra redit *' %ext Steps

III >e<ie&in) -nd CritiAuin) Code


** Deconstructin) "K&R C" ...1 An &7erall ritiCue &@ orre#tness ...2 ha"ter 1 *$a!"les

Contents
I Basic Skills
1 Exercise 0: The Setup 1.1 Linu$ 1.2 %a# &S' 1.3 Windows 1.4 Te$t *ditor 1.4.1 WAR6+6:D 1o 6ot ,se An +1*

2 Exercise 1: Dust Off That Compiler 2.1 What You Should See 2.2 How To Break +t 2.3 *$tra redit 3 Exercise : "ake Is #our P$thon %o& 3.1 ,sin- %ake 3.2 What You Should See 3.3 How To Break +t 3.4 *$tra redit 4 Exercise !: (ormatted Printin) 4.1 What You Should See 4.2 *$ternal Resear#h 4.3 How To Break +t 4.4 *$tra redit

5 Exercise ': Introducin) +al)rind 5.1 +nstallin- /al-rind 5.2 ,sin- /al-rind 5.3 What You Should See 5.4 *$tra redit 6 Exercise *: The Structure Of - C Pro)ram 6.1 What You Should See 6.2 Breakin- +t 1own 6.3 *$tra redit 7 Exercise ,: T$pes Of +aria/les 7.1 What You Should See 7.2 How To Break +t 7.3 *$tra redit 8 Exercise .: "ore +aria/les1 Some "ath 8.1 What You Should See 8.2 How To Break +t 8.3 *$tra redit 9 Exercise 0: Si3es -nd -rra$s 9.1 What You Should See 9.2 How To Break +t 9.3 *$tra redit 10 Exercise 2: -rra$s -nd Strin)s 10.1 What You Should See 10.2 How To Break +t 10.3 *$tra redit 11 Exercise 10: -rra$s Of Strin)s1 4oopin) 11.1 What You Should See 11.1.1 ,nderstandin- Arrays &@ Strin-s 11.2 How To Break +t 11.3 *$tra redit

Introduction: The Cartesian Dream Of C


Whate7er + ha7e u" till now a##e"ted as !ost true and assured + ha7e -otten either @ro! the senses or throu-h the senses. But @ro! ti!e to ti!e + ha7e @ound that the senses de#ei7e; and it is "rudent ne7er to trust #o!"letely those who ha7e de#ei7ed us e7en on#e. ERene 1es#artes; %editations &n >irst 5hiloso"hyF If there ever were a quote that described progra i!g with "# it wou$d be this. %o a!& progra ers# this a'es " scar& a!d evi$. It is the (evi$# )ata!# the tric'ster *o'i co e to destro& &our productivit& with his seductive ta$' of poi!ters a!d direct access to the achi!e. %he!# o!ce this co putatio!a$ *ucifer has &ou hoo'ed# he destro&s &our wor$d with the evi$ +segfau$t+ a!d $aughs as he revea$s the tric'er& i! &our bargai! with hi . ,ut# " is !ot to b$a e for this state of affairs. -o & frie!ds# &our co puter a!d the .perati!g )&ste co!tro$$i!g it are the rea$ tric'sters. %he& co!spire to hide their true i!!er wor'i!gs fro &ou so that &ou ca! !ever rea$$& '!ow what is goi!g o!. %he " progra i!g $a!guage/s o!$& fai$i!g is givi!g &ou access to what is rea$$& there# a!d te$$i!g &ou the co$d hard raw truth. " gives &ou the red pi$$. " pu$$s the curtai! bac' to show &ou the wi0ard. C is truth. 1h& use " the! if it/s so da!gerous2 ,ecause " gives &ou power over the fa$se rea$it& of abstractio! a!d $iberates &ou fro stupidit&.

What ou Will Learn


%he purpose of this boo' is to get &ou stro!g e!ough i! " that &ou/$$ be ab$e to write &our ow! software i! it# or odif& so eo!e e$se/s code. 3t the e!d of the boo' we actua$$& ta'e

1. 2. (. ). .. 0.

code fro a ore fa ous boo' ca$$ed "K&R C" a!d code review it usi!g what &ou/ve $ear!ed. %o get to this stage &ou/$$ have to $ear! a few thi!gs4 The 8asi#s o@ synta$ and idio!s. o!"ilation; !ake @iles; linkers. >indin- 8u-s and "re7entin- the!. 1e@ensi7e #odin- "ra#ti#es. Breakin- #ode. Writin- 8asi# ,ni$ syste!s so@tware. ,& the fi!a$ chapter &ou wi$$ have ore tha! e!ough a u!itio! to tac'$e basic s&ste s software# $ibraries# a!d other s a$$er pro5ects.

Ho! To "ead This #oo$


%his boo' is i!te!ded for progra ers who have $ear!ed at $east o!e other progra i!g $a!guage. I refer &ou to Learn 5ython The Hard Way or to Learn Ru8y The Hard Way if &ou have!/t $ear!ed a progra i!g $a!guage &et. %hose two boo's are for tota$ begi!!ers a!d wor' ver& we$$. .!ce &ou/ve do!e those the! &ou ca! co e bac' a!d start this boo'. 6or those who/ve a$read& $ear!ed to code# this boo' a& see stra!ge at first. It/s !ot $i'e other boo's where &ou read paragraph after paragraph of prose a!d the! t&pe i! a bit of code here a!d there. I!stead I have &ou codi!g right awa& a!d the! I e7p$ai! what &ou 5ust did. %his wor's better because it/s easier to e7p$ai! so ethi!g &ou/ve a$read& e7perie!ced. ,ecause of this structure# there are a few ru$es &ou must fo$$ow i! this boo'4 Ty"e in all o@ the #ode. 1o not #o"yA"asteG Ty"e the #ode in e$a#tly; e7en the #o!!ents. :et it to run and !ake sure it "rints the sa!e out"ut. +@ there are 8u-s @i$ the!. 1o the e$tra #redit 8ut itHs alri-ht to ski" ones you #anHt @i-ure out.

1. 2. (. ). ..

0.

Always try to @i-ure it out @irst 8e@ore tryin- to -et hel". If &ou fo$$ow these ru$es# do ever&thi!g i! the boo'# a!d sti$$ ca!/t code " the! &ou at $east tried. It/s !ot for ever&o!e# but the act of tr&i!g wi$$ a'e &ou a better progra er.

The Core Com%etencies


I/ goi!g to guess that &ou co e fro a $a!guage for wea'$i!gs 1. .!e of those +usab$e+ $a!guages that $ets &ou get awa& with s$opp& thi!'i!g a!d ha$f8assed hac'er& $i'e 9&tho! or :ub&. .r# a&be &ou use a $a!guage $i'e *isp that prete!ds the co puter is so e pure$& fu!ctio!a$ fa!tas& $a!d with padded wa$$s for $itt$e babies. ;a&be &ou/ve $ear!ed 9ro$og a!d &ou thi!' the e!tire wor$d shou$d 5ust be a database that &ou wa$' arou!d i! $oo'i!g for c$ues. <ve! worse# I/ betti!g &ou/ve bee! usi!g a! I(<# so &our brai! is ridd$ed with e or& ho$es a!d &ou ca!/t eve! t&pe out a! e!tire fu!ctio!/s !a e without hitti!g "%:*8)93"< ever& 3 characters &ou t&pe. -o atter what &our bac'grou!d# &ou are probab$& bad at four s'i$$s4 >eadin) -nd 5ritin) This is es"e#ially true i@ you use an +1*; 8ut -enerally + @ind "ro-ra!!ers do too !u#h Iski!!in-I and ha7e "ro8le!s readin- @or #o!"rehension. TheyHll ski! #ode they need to understand in detail and think they understand it when they really donHt. &ther lan-ua-es "ro7ide tools that also let the! a7oid a#tually writin- any #ode; so when @a#ed with a lan-ua-e like they 8reak down. Si!"lest thin- to do is 9ust understand everyone has this "ro8le!; and you #an @i$ it 8y @or#inyoursel@ to slow down and 8e !eti#ulous a8out your readin- and writin-. At @irst itHll @eel "ain@ul and annoyin-; 8ut take @reCuent 8reaks; and then e7entually itHll 8e easy to do. -ttention To Detail *7eryone is 8ad at this; and itHs the 8i--est #ause o@ 8ad so@tware. &ther lan-ua-es let you -et away with not "ayin- attention; 8ut de!ands

your @ull attention 8e#ause it is ri-ht in the !a#hine and the !a#hine is 7ery "i#ky. With there is no Ikind o@ si!ilarI or I#lose enou-hI; so you need to "ay attention. 1ou8le #he#k your work. Assu!e e7erythinyou write is wron- until you "ro7e itHs ri-ht. Spottin) Differences A key "ro8le! "eo"le @ro! other lan-ua-es ha7e is their 8rain has 8een trained to s"ot di@@eren#es in that lan-ua-e; not in . When you #o!"are #ode youH7e written to !y e$er#ise #ode your eyes will 9u!" ri-ht o7er #hara#ters you think donHt !atter or that arenHt @a!iliar. +Hll 8e -i7in- you strate-ies that @or#e you to see your !istakes; 8ut kee" in !ind that i@ your #ode is not exactly like the #ode in this 8ook it is wron-. Plannin) -nd De/u))in) + lo7e other easier lan-ua-es 8e#ause + #an 9ust han- out. + ty"e the ideas + ha7e into their inter"reter and see results i!!ediately. TheyHre -reat @or 9ust ha#kin- out ideas; 8ut ha7e you noti#ed that i@ you kee" doin- Iha#k until it worksI e7entually nothin- works? is harder on you 8e#ause it reCuires you to "lan out what youHll #reate @irst. Sure; you #an ha#k @or a 8it; 8ut you ha7e to -et serious !u#h earlier in than other lan-ua-es. +Hll 8e tea#hin- you ways to "lan out key "arts o@ your "ro-ra! 8e@ore you start #odin-; and this will ho"e@ully !ake you a 8etter "ro-ra!!er at the sa!e ti!e. *7en 9ust a little "lannin- #an s!ooth thin-s out down the road. *ear!i!g " a'es &ou a better progra er because &ou are forced to dea$ with these issues ear$ier a!d ore freque!t$&. =ou ca!/t be s$opp& a!d ha$f8assed about what &ou write or !othi!g wi$$ wor'. %he adva!tage of " is it/s a si p$e $a!guage &ou ca! figure out o! &our ow!# which a'es it a great $a!guage for $ear!i!g about the achi!e a!d getti!g stro!ger i! these core progra er s'i$$s. " is harder tha! so e other $a!guages# but that/s o!$& because "/s !ot hidi!g thi!gs fro &ou that those other $a!guages tr& a!d fai$ to obfuscate.

License

%his boo' is free for &ou to read# but u!ti$ I/ do!e &ou ca!/t distribute it or odif& it. I !eed to a'e sure that u!fi!ished copies of it do !ot get out a!d ess up a stude!t o! accide!t.

Part I
#asic &$ills
1 Exercise 0: The Setup 1.1 Linu$ 1.2 %a# &S' 1.( Windows 1.) Te$t *ditor Exercise 1: Dust Off That Compiler 2.1 What You Should See 2.2 How To Break +t 2.( *$tra redit ! Exercise : "ake Is #our P$thon %o& (.1 ,sin- %ake (.2 What You Should See (.( How To Break +t (.) *$tra redit ' Exercise !: (ormatted Printin) ).1 What You Should See ).2 *$ternal Resear#h ).( How To Break +t ).) *$tra redit * Exercise ': Introducin) +al)rind ..1 +nstallin- /al-rind ..2 ,sin- /al-rind ..( What You Should See ..) *$tra redit , Exercise *: The Structure Of - C Pro)ram

0.1 What You Should See 0.2 Breakin- +t 1own 0.( *$tra redit . Exercise ,: T$pes Of +aria/les 2.1 What You Should See 2.2 How To Break +t 2.( *$tra redit 0 Exercise .: "ore +aria/les1 Some "ath 3.1 What You Should See 3.2 How To Break +t 3.( *$tra redit 2 Exercise 0: Si3es -nd -rra$s 4.1 What You Should See 4.2 How To Break +t 4.( *$tra redit 10 Exercise 2: -rra$s -nd Strin)s 10.1 What You Should See 10.2 How To Break +t 10.( *$tra redit 11 Exercise 10: -rra$s Of Strin)s1 4oopin) 11.1 What You Should See 11.2 How To Break +t 11.( *$tra redit 1 Exercise 11: 5hile64oop -nd Boolean Expressions 12.1 What You Should See 12.2 How To Break +t 12.( *$tra redit 1! Exercise 1 : If1 Else6If1 Else 1(.1 What You Should See 1(.2 How To Break +t 1(.( *$tra redit 1' Exercise 1!: S&itch Statement 1).1 What You Should See

1).2 How To Break +t 1).( *$tra redit 1* Exercise 1': 5ritin) -nd 7sin) (unctions 1..1 What You Should See 1..2 How To Break +t 1..( *$tra redit 1, Exercise 1*: Pointers Dreaded Pointers 10.1 What You Should See 10.2 *$"lainin- 5ointers 10.( 5ra#ti#al 5ointer ,sa-e 10.) The 5ointer Le$i#on 10.. 5ointers Are 6ot Arrays 10.0 How To Break +t 10.2 *$tra redit 1. Exercise 1,: Structs -nd Pointers To Them 12.1 What You Should See 12.2 *$"lainin- Stru#tures 12.( How To Break +t 12.) *$tra redit 10 Exercise 1.: 8eap -nd Stack "emor$ -llocation 13.1 What You Should See 13.2 Hea" 7s. Sta#k Allo#ation 13.( How To Break +t 13.) *$tra redit 12 Exercise 10: Pointers To (unctions 14.1 What You Should See 14.2 How To Break +t 14.( *$tra redit 0 Exercise 12: - Simple O/9ect S$stem 20.1 How The 55 Works 20.2 The 5rototy"e &89e#t Syste! 20.( The :a!e +!"le!entation 20.) What You Should See

20.. Auditin- The :a!e 20.0 *$tra redit 1 Exercise 0: :ed;s -&esome De/u) "acros 21.1 The *rror Handlin- 5ro8le! 21.2 The 1e8u- %a#ros 21.( ,sin- d8-.h 21.) What You Should See 21.. How The 55 *$"ands %a#ros 21.0 *$tra redit Exercise 1: -d<anced Data T$pes -nd (lo& Control 22.1 A7aila8le 1ata Ty"es 22.2 A7aila8le &"erators 22.( A7aila8le ontrol Stru#tures ! Exercise : The Stack1 Scope1 -nd =lo/als 2(.1 What You Should See 2(.2 S#o"e; Sta#k; And Bu-s 2(.( How To Break +t 2(.) *$tra redit ' Exercise !: "eet Duff;s De<ice 2).1 What You Should See 2).2 Sol7in- The 5u<<le 2).( *$tra redit * Exercise ': Input1 Output1 (iles 2..1 What You Should See 2..2 How To Break +t 2..( The +=& >un#tions 2..) *$tra redit , Exercise *: +aria/le -r)ument (unctions 20.1 What You Should See 20.2 How To Break +t 20.( *$tra redit . Exercise ,: 5rite - (irst >eal Pro)ram 22.1 What +s devpkg?

22.2 5ro9e#t Layout 22.( The %ake@ile 22.) The Sour#e >iles 22.. The %idATer! *$a!

Chapter 1
'(ercise ): The &etu%
I! this chapter &ou get &our s&ste setup to do " progra i!g. %he good !ews for a!&o!e usi!g *i!u7 or ;ac .)> is that &ou are o! a s&ste desig!ed for progra i!g i! ". %he authors of the " $a!guage were a$so i!stru e!ta$ i! the creatio! of the ?!i7 operati!g s&ste # a!d both *i!u7 a!d .)> are based o! ?!i7. I! fact# the i!sta$$ wi$$ be i!credib$& eas&. I have so e bad !ews for users of 1i!dows4 $ear!i!g " o! 1i!dows is pai!fu$. =ou ca! write " code for 1i!dows# that/s !ot a prob$e . %he prob$e is a$$ of the $ibraries# fu!ctio!s# a!d too$s are 5ust a $itt$e +off+ fro ever&o!e e$se i! the " wor$d. " ca e fro ?!i7 a!d is uch easier o! a ?!i7 p$atfor . It/s 5ust a fact of $ife that &ou/$$ have to accept I/ afraid. I wa!ted to get this bad !ews out right awa& so that &ou do!/t pa!ic. I/ !ot sa&i!g to avoid 1i!dows e!tire$&. I a however sa&i!g that# if &ou wa!t to have the easiest ti e $ear!i!g "# the! it/s ti e to bust out so e ?!i7 a!d get dirt&. %his cou$d a$so be rea$$& good for &ou# si!ce '!owi!g a $itt$e bit of ?!i7 wi$$ a$so teach &ou so e of the idio s of " progra i!g a!d e7pa!d &our s'i$$s. %his a$so ea!s that for ever&o!e &ou/$$ be usi!g the command line. =ep# I said it. =ou/ve gotta get i! there a!d t&pe co a!ds at the co puter. (o!/t be afraid though because I/$$ be te$$i!g &ou what to t&pe a!d what it shou$d $oo' $i'e# so &ou/$$ actua$$& be $ear!i!g quite a few i!d e7pa!di!g s'i$$s at the sa e ti e.

1B1 Linu(
.! ost *i!u7 s&ste s &ou 5ust have to i!sta$$ a few pac'ages. 6or (ebia! based s&ste s# $i'e ?bu!tu &ou shou$d 5ust have to i!sta$$ a few thi!gs usi!g these co a!ds4
Source 1: Installing Requirements On Ubuntu 1$ sudo apt-get install build-essential

%he above is a! e7a p$e of a co a!d $i!e pro pt# so to get to where &ou ca! ru! that# fi!d &our +%er i!a$+ progra a!d ru! it first. %he! &ou/$$ get a she$$ pro pt si i$ar to the /J/ above a!d ca! t&pe that co a!d i!to it. Do not type the ' '! "ust the stuff after it. @ere/s how &ou wou$d i!sta$$ the sa e setup o! a! :9; based *i!u7 $i'e 6edora4
Source : Installing Requirements On #edora 1$ su -c "yum groupinstall development-tools"

.!ce &ou/ve ru! that# &ou shou$d be ab$e to do the first <7ercise i! this boo' a!d it/$$ wor'. If !ot the! $et e '!ow.

1B Mac O&*
.! ;ac .)> the i!sta$$ is eve! easier. 6irst# &ou/$$ !eed to either dow!$oad the $atest XCode fro 3pp$e# or fi!d &our i!sta$$ (A( a!d i!sta$$ it fro there. %he dow!$oad wi$$ be assive a!d cou$d ta'e forever# so I reco e!d i!sta$$i!g fro the (A(. 3$so# search o!$i!e for +i!sta$$i!g 7code+ for i!structio!s o! how to do it. .!ce &ou/re do!e i!sta$$i!g >"ode# a!d probab$& restarti!g &our co puter if it did!/t a'e &ou do that# &ou ca! go fi!d &our %er i!a$ progra a!d get it put i!to &our (oc'. =ou/$$ be usi!g %er i!a$ a $ot i! the boo'# so it/s good to put it i! a ha!d& $ocatio!.

1B! Windo!s
6or 1i!dows users I/$$ show &ou how to get a basic ?bu!tu *i!u7 s&ste up a!d ru!!i!g i! a virtua$ achi!e so that &ou

ca! sti$$ do a$$ of & e7ercises# but avoid a$$ the pai!fu$ 1i!dows i!sta$$atio! prob$e s. ... have to figure this o!e out.

1B' Te(t 'ditor


%he choice of te7t editor for a progra er is a tough o!e. 6or begi!!ers I te$$ the to 5ust use:edit si!ce it/s si p$e a!d wor's for code. @owever# it does!/t wor' i! certai! i!ter!atio!a$i0ed situatio!s# a!d cha!ces are &ou a$read& have a favorite te7t editor if &ou/ve bee! progra i!g for a whi$e. 1ith this i! i!d# I wa!t &ou to tr& out a few of the sta!dard progra er te7t editors for &our p$atfor a!d the! stic' with the o!e that &ou $i'e best. If &ou/ve bee! usi!g B<dit a!d $i'e it the! stic' with it. If &ou wa!t to tr& so ethi!g differe!t# the! tr& it out rea$ quic' a!d pic' o!e. %he ost i porta!t thi!g is do not get stuc$ pic$ing the perfect editor . %e7t editors a$$ 5ust 'i!d of suc' i! odd wa&s. Cust pic' o!e# stic' with it# a!d if &ou fi!d so ethi!g e$se &ou $i'e tr& it out. (o!/t spe!d da&s o! e!d co!figuri!g it a!d a'i!g it perfect. )o e te7t editors to tr& out are4 :edit on Linu$ and &S'. Te$tWran-ler on &S'. 6ano whi#h runs in Ter!inal and works nearly e7erywhere. *!a#s and *!a#s @or &S'. Be "re"ared to do so!e learnin- thou-h. /i! and %a#/i! %here is probab$& a differe!t editor for ever& perso! out there# but these are 5ust a few of the free o!es that I '!ow wor'. %r& a few out# a!d a&be so e co ercia$ o!es u!ti$ &ou fi!d o!e that &ou $i'e.

1. 2. (. ). ..

1B'B1 WA"+I+,: Do +ot -se An ID'


3! I(<# or +I!tegrated (eve$op e!t <!viro! e!t+ wi$$ tur! &ou stupid. %he& are the worst too$s if &ou wa!t to be a good progra er because the& hide what/s goi!g o! fro &ou# a!d

&our 5ob is to '!ow what/s goi!g o!. %he& are usefu$ if &ou/re tr&i!g to get so ethi!g do!e a!d the p$atfor is desig!ed arou!d a particu$ar I(<# but for $ear!i!g to code " Da!d a!& other $a!guagesE the& are poi!t$ess.
%ote 1: ID%s and &uitar 'ablature +@ youH7e "layed -uitar then you know what ta8lature is; 8ut @or e7eryone else let !e e$"lain. +n !usi# thereHs an esta8lished notation #alled the Ista@@ notationI. +tHs a -eneri#; 7ery old; and uni7ersal way to write down what so!eone should "lay on an instru!ent. +@ you "lay "iano this notation is @airly easy to use; sin#e it was #reated !ostly @or "iano and #o!"osers. :uitar howe7er is a weird instru!ent that doesnHt really work with notation; so -uitarists ha7e an alternati7e notation #alled Ita8latureI. What ta8lature does is; rather than tell you the note to "lay; it tells you the @ret and strin- you should "lay at that ti!e. You #ould learn whole son-s without e7er knowin- a8out a sin-le thin- youHre "layin-. %any "eo"le do it this way; 8ut i@ you want to know (hat youHre "layin-; then ta8lature is "ointless. +t !ay 8e harder than ta8lature; 8ut traditional notation tells you how to "lay the music rather than 9ust how to "lay the -uitar. With traditional notation + #an walk o7er to a "iano and "lay the sa!e son-. + #an "lay it on a 8ass. + #an "ut it into a #o!"uter and desi-n whole s#ores around it. With ta8lature + #an 9ust "lay it on a -uitar. +1*s are like ta8lature. Sure; you #an #ode "retty Cui#kly; 8ut you #an only #ode in that one lan-ua-e on that one "lat@or!. This is why #o!"anies lo7e sellin- the! to you. They know youHre la<y; and sin#e it only works on their "lat@or! theyH7e -ot you lo#ked in 8e#ause you are la<y. The way you 8reak the #y#le is you su#k it u" and @inally learn to #ode without an +1*. A "lain editor; or a "ro-ra!!erHs editor like /i! or *!a#s; !akes you work with the #ode. +tHs a little harder; 8ut the end result is you #an work with any #ode; on any #o!"uter; in any lan-ua-e; and you know whatHs -oin- on.

ha"ter 2
'(ercise .: Dust Off That Com%iler
@ere is a si p$e first progra &ou ca! a'e i! "4
Source !: ex).c 1 int main(int argc, char *argv[]) 2 { ( puts("Hello world.");
) . 0

return 0; }

=ou ca! put this i!to a


Source ': *uilding ex) 1$ make ex1 2cc ex1.c
-o ex1

ex1.c

the! t&pe4

=our co puter a& use a s$ight$& differe!t co a!d# but the e!d resu$t shou$d be a fi$e !a ed ex1that &ou ca! ru!.

2.1 What ou &hould &ee


=ou ca! !ow ru! the progra
Source *: Running ex) 1$ ./ex1 2Hello world.

a!d see the output.

If &ou do!/t the! go bac' a!d fi7 it.

2.2 Ho! To #rea$ It


I! this boo' I/ goi!g to have a s a$$ sectio! for each progra o! how to brea' the progra . I/$$ have &ou do odd thi!gs to the progra s# ru! the i! weird wa&s# or cha!ge code so that &ou ca! see crashes a!d co pi$er errors. 6or this progra # rebui$d it with a$$ co pi$er war!i!gs o!4
Source ,: *uilding ex) (ith +,all 1$ rm ex1 2$ CF !"#$"-%all" make ex1 (cc -%all ex1.c -o ex1 )ex1.c& 'n (unction )main)& .ex1.c&*& warning& implicit declaration o( (unction )puts) 0$ ./ex1 2Hello world. 3$

-ow &ou are getti!g a war!i!g that sa&s the fu!ctio! +puts+ is i p$icit$& dec$ared. %he " co pi$er is s art e!ough to figure out what &ou wa!t# but &ou shou$d be getti!g rid of a$$ co pi$er war!i!gs whe! &ou ca!. @ow &ou do this is add the fo$$owi!g $i!e to the top of ex1.c a!d reco pi$e4
1+include ,stdio.-.

-ow do the a'e agai! $i'e &ou 5ust did a!d &ou/$$ see the war!i!g go awa&.

2.( '(tra Credit

&"en the ex1 @ile in your te$t editor and #han-e or delete rando! "arts. Try runnin- it and see what ha""ens. 2. 5rint out . !ore lines o@ te$t or so!ethin- !ore #o!"le$ than hello world. (. Run man * puts and read a8out this @un#tion and !any others.
1.

ha"ter (
'(ercise /: Ma$e Is our Python +o!
I! 5ython &ou ra! progra s b& 5ust t&pi!g pyt-on a!d the code &ou wa!ted to ru!. %he 9&tho! i!terpreter wou$d 5ust ru! the # a!d i port a!& other $ibraries a!d thi!gs &ou !eeded o! the f$& as it ra!. " is a differe!t beast co p$ete$& where &ou have to compile &our source fi$es a!d a!ua$$& stitch the together i!to a bi!ar& that ca! ru! o! its ow!. (oi!g this a!ua$$& is a pai!# a!d i! the $ast e7ercise &ou 5ust ra! make to do it. I! this e7ercise# &ou/re goi!g to get a crash course i! B-? a'e# a!d &ou/$$ be $ear!i!g to use it as &ou $ear! ". ;a'e wi$$ for the rest of this boo'# be &our 9&tho!. It wi$$ bui$d &our code# a!d ru! &our tests# a!d set thi!gs up a!d do a$$ the stuff for &ou that 9&tho! !or a$$& does. %he differe!ce is# I/ goi!g to show &ou s arter ;a'efi$e wi0ardr&# where &ou do!/t have to specif& ever& stupid $itt$e thi!g about &our " progra to get it to bui$d. I wo!/t do that i! this e7ercise# but after &ou/ve bee! usi!g +bab& a'e+ for a whi$e# I/$$ show &ou + aster a'e+.

(.1 -sing Ma$e


%he first stage of usi!g a'e is to 5ust use it to bui$d progra s it a$read& '!ows how to bui$d. ;a'e has decades of '!ow$edge o! bui$di!g a wide variet& of fi$es fro other fi$es. I! the $ast e7ercise &ou did this a$read& usi!g co a!ds $i'e this4

Source .: *uilding ex) (ith +,all 1$ make ex1 2+ or t-is one too ($ CF !"#$"-%all" make ex1

1. 2. (. ). ..

I! the first co a!d &ou/re te$$i!g a'e# +I wa!t a fi$e !a ed e71 to be created.+ ;a'e the! does the fo$$owi!g4 1oes the @ile ex1 e$ist already? 6o. &k; is there another @ile that starts with ex1? Yes; itHs #alled ex1.c. 1o + know how to 8uild .c @iles? Yes; + run this #o!!and cc ex1.c -o ex1 to 8uild the!. + shall !ake you one ex1 8y usin- cc to 8uild it @ro! ex1.c. %he seco!d co a!d i! the $isti!g above is a wa& to pass + odifiers+ to the a'e co a!d. If &ou/re !ot fa i$iar with how the ?!i7 she$$ wor's# &ou ca! create these +e!viro! e!t variab$es+ which wi$$ get pic'ed up b& progra s &ou ru!. )o eti es &ou do this with a co a!d $i'eexport CF !"#$"%all" depe!di!g o! the she$$ &ou use. =ou ca! however a$so 5ust put the before the co a!d &ou wa!t to ru!# a!d that e!viro! e!t variab$e wi$$ be set o!$& whi$e that co a!d ru!s. I! this e7a p$e I did CF !"#$"-%all" make ex1 so that it wou$d add the co a!d $i!e optio! -%all to thecc co a!d that make !or a$$& ru!s. %hat co a!d $i!e optio! te$$s the co pi$er cc to report a$$ war!i!gs Dwhich i! a sic' twist of fate is!/t actua$$& a$$ the war!i!gs possib$eE. =ou ca! actua$$& get prett& far with 5ust that wa& of usi!g make# but $et/s get i!to a'i!g a Makefileso &ou ca! u!dersta!d a'e a $itt$e better. %o start off# create a fi$e with 5ust this i! it4

Source 0: - simple .a$efile 1CF !"#$-%all -g 2 (clean& ) rm -( ex1

)ave this fi$e as Makefile i! &our curre!t director&. ;a'e auto atica$$& assu es there/s a fi$e ca$$edMakefile a!d wi$$ 5ust

ru! it. 3$so# ,-R/I/&0 .a$e sure you are only entering '-* characters! not mixtures of '-* and spaces. %his Makefile is showi!g &ou so e !ew stuff with a'e. 6irst we set CFLAGS i! the fi$e so we !ever have to set it agai!# as we$$ as addi!g the -g f$ag to get debuggi!g. %he! we have a sectio! !a edclean which te$$s a'e how to c$ea! up our $itt$e pro5ect. ;a'e sure it/s i! the sa e director& as &our ex1.c fi$e# a!d the! ru! these co a!ds4
Source 2: Running a simple .a$efile 1$ make clean 2$ make ex1

(.2 What ou &hould &ee


If that wor'ed the! &ou shou$d see this4
Source 10: #ull build (ith .a$efile 1$ make clean 2rm -( ex1 ($ make ex1 )cc -%all -g ex1.c -o ex1 .ex1.c& 'n (unction )main)& 0ex1.c&*& warning& implicit declaration o( (unction )puts) 2$

@ere &ou ca! see that I/ ru!!i!g make clean which te$$s a'e to ru! our clean target. Bo $oo' at the ;a'efi$e agai! a!d &ou/$$ see that u!der this I i!de!t a!d the! I put the she$$ co a!ds I wa!t maketo ru! for e. =ou cou$d put as a!& co a!ds as &ou wa!ted i! there# so it/s a great auto atio! too$.
%ote : Did 1ou #ix ex).c2 +@ you @i$ed ex1.c to ha7e +include ,stdio.-. then your out"ut will not ha7e the warnin- Ewhi#h should really 8e an errorF a8out "uts. + ha7e the error here 8e#ause + didnHt @i$ it.

-otice a$so that# eve! though we do!/t e!tio! ex1 i! the Makefile# make sti$$ '!ows how to bui$d itplus use our specia$ setti!gs.

(.( Ho! To #rea$ It


%hat shou$d be e!ough to get &ou started# but first $et/s brea' this a'e fi$e i! a particu$ar wa& so &ou ca! see what

happe!s. %a'e the $i!e rm -( ex1 a!d dede!t it D ove it a$$ the wa& $eftE so &ou ca! see what happe!s. :eru! make clean a!d &ou shou$d get so ethi!g $i'e this4
Source 11: *ad ma$e run 1$ make clean 2/ake(ile&0& 111 missing separator.
#top.

3$wa&s re e ber to i!de!t# a!d if &ou get weird errors $i'e this the! doub$e chec' &ou/re co!siste!t$& usi!g tab characters si!ce so e a'e varia!ts are ver& pic'&.

(.) '(tra Credit


1. 2. (.

).
..

reate an all& ex1 tar-et that will 8uild ex1 with 9ust the #o!!and make. Read man make to @ind out !ore in@or!ation on how to run it. Read man cc to @ind out !ore in@or!ation on what the @la-s -%all and g do. Resear#h %ake@iles online and see i@ you #an i!"ro7e this one e7en !ore. >ind a Makefile in another "ro9e#t and try to understand what itHs doin-.

ha"ter )
'(ercise 0: 1ormatted Printing
Feep that Makefile arou!d si!ce it/$$ he$p &ou spot errors a!d we/$$ be addi!g to it whe! we !eed to auto ate ore thi!gs. ;a!& progra i!g $a!guages use the " wa& of for atti!g output# so $et/s tr& it4
Source 1 : ex3.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10

int main() { int age = 10; int -eig-t = 72; print(("' am 2d years old.3n", age); print(("' am 2d inc-es tall.3n", -eig-t);

11 12

return 0; }

1.

2. (. ). .. 0.

.!ce &ou have that# do the usua$ make e"# to bui$d it a!d ru! it. ;a'e sure &ou fix all (arnings. %his e7ercise has a who$e $ot goi!g o! i! a s a$$ a ou!t of code so $et/s brea' it dow!4 >irst youHre in#ludin- another Iheader @ileI #alled t!i".h. This tells the #o!"iler that youHre -oin- to use the Istandard +n"ut=&ut"ut @un#tionsI. &ne o@ those is p$int%. Then youHre usin- a 7aria8le na!ed age and settin- it to 10. 6e$t youHre usin- a 7aria8le eig t and settin- it to 22. Then you use the p$int% @un#tion to "rint the a-e and hei-ht o@ the tallest 10 year old on the "lanet. +n the p$int% youHll noti#e youHre "assin- in a strin-; and itHs a @or!at strin- like in !any other lan-ua-es. A@ter this @or!at strin-; you "ut the 7aria8les that should 8e Ire"la#edI into the @or!at strin- 8yp$int%. %he resu$t of doi!g this is &ou are ha!di!g p$int% so e variab$es a!d it is co!structi!g a !ew stri!g the! pri!ti!g that !ew stri!g to the ter i!a$.

).1 What ou &hould &ee


1he! &ou do the who$e bui$d &ou shou$d see so ethi!g $i'e this4
Source 1!: *uilding and running ex3.c 1$ make ex* 2cc -%all -g ex*.c -o ex* ($ ./ex* )' am 14 years old. .' am 56 inc-es tall. 0$

9rett& soo! I/ goi!g to stop te$$i!g &ou to ru! make a!d what the bui$d $oo's $i'e# so p$ease a'e sure &ou/re getti!g this right a!d that it/s wor'i!g.

).2 '(ternal "esearch

I! the %xtra Credit sectio! of each e7ercise I a& have &ou go fi!d i!for atio! o! &our ow! a!d figure thi!gs out. %his is a! i porta!t part of bei!g a se$f8sufficie!t progra er. If &ou co!sta!t$& ru! to as' so eo!e a questio! before tr&i!g to figure it out first the! &ou !ever $ear! to so$ve prob$e s i!depe!de!t$&. %his $eads to &ou !ever bui$di!g co!fide!ce i! &our s'i$$s a!d a$wa&s !eedi!g so eo!e e$se arou!d to do &our wor'. %he wa& &ou brea' this habit is to force &ourse$f to tr& to a!swer &our ow! questio!s first# a!d to co!fir that &our a!swer is right. =ou do this b& tr&i!g to brea' thi!gs# e7peri e!ti!g with &our possib$e a!swer# a!d doi!g &our ow! research. 6or this e7ercise I wa!t &ou to go o!$i!e a!d fi!d out all of the p$int% escape codes a!d for at seque!ces. <scape codes are 3n or 3t that $et &ou pri!t a !ew$i!e or tab Drespective$&E. 6or at seque!ces are the 2s or 2d that $et &ou pri!t a stri!g or a i!teger. 6i!d a$$ of the o!es avai$ab$e# how &ou ca! odif& the # a!d what 'i!d of +precisio!s+ a!d widths &ou ca! do. 6ro !ow o!# these 'i!ds of tas's wi$$ be i! the <7tra "redit a!d &ou shou$d do the .

).( Ho! To #rea$ It


%r& a few of these wa&s to brea' this progra # which a& or a& !ot cause it to crash o! &our co puter4 1. Take the age 7aria8le out o@ the @irst p$int% #all then re#o!"ile. You should -et a #ou"le o@ warnin-s. 2. Run this new "ro-ra! and it will either #rash; or "rint out a really #ra<y a-e. (. 5ut the p$int% 8a#k the way it was; and then donHt set age to an initial 7alue 8y #han-in- that line to int age7 then re8uild and run a-ain.
Source 1': *rea$ing ex3.c 1+ edit ex*.c to break print( 2$ make ex*

(cc -%all -g ex*.c -o ex* )ex*.c& 'n (unction )main)& .ex*.c&8& warning& too (ew arguments (or (ormat 0ex*.c&9& warning& unused variable )age) 2$ ./ex* 3' am -:1:4:609; years old. 4' am 56 inc-es tall. 10+ edit ex*.c again to (ix print(< but don)t init age 11$ make ex* 12cc -%all -g ex*.c -o ex* 1(ex*.c& 'n (unction )main)& 1)ex*.c&8& warning& )age) is used uninitiali=ed in t-is (unction 1.$ ./ex* 10' am 4 years old. 12' am 56 inc-es tall. 13$

).) '(tra Credit


>ind as !any other ways to 8reak ex#.c as you #an. 2. Run man * print( and read a8out the other HKH @or!at #hara#ters you #an use. These should look @a!iliar i@ you used the! in other lan-ua-es Ep$int% is where they #o!e @ro!F. (. Add ex# to your MakefileHs all list. ,se this to make clean all and 8uild all your e$er#ises so @ar. ). Add ex# to your MakefileHs clean list as well. 6ow use make clean will re!o7e it when you need to.
1.

ha"ter .
'(ercise 2: Introducing 3algrind
It/s ti e to $ear! about a!other too$ &ou wi$$ $ive a!d die b& as &ou $ear! " ca$$ed &alg$ind. I/ i!troduci!g &alg$ind to &ou !ow because &ou/re goi!g to use it fro !ow o! i! the +@ow %o ,rea' It+ sectio!s of each e7ercise. &alg$ind is a progra that ru!s &our progra s# a!d the! reports o! a$$ of the horrib$e ista'es &ou ade. It/s a wo!derfu$ free piece of software that I use co!sta!t$& whi$e I write " code. :e e ber i! the $ast e7ercise that I to$d &ou to brea' &our code b& re ovi!g o!e of the argu e!ts to p$int%2 It pri!ted out so e fu!'& resu$ts# but I did!/t te$$ &ou wh& it pri!ted

those resu$ts out. I! this e7ercise we/re goi!g to use &alg$ind to fi!d out wh&.
%ote !: ,hat's ,ith -ll 'he 'ools These @irst @ew e$er#ises are !i$in- so!e essential tools the rest o@ the 8ook needs with learnina little 8it o@ #ode. The reason is that !ost o@ the @olks who read this 8ook are not @a!iliar with #o!"iled lan-ua-es; and de@initely not with auto!ation and hel"@ul tools. By -ettin- you to use make and &alg$ind ri-ht now + #an then use the! to tea#h you your 8u-s early. A@ter this e$er#ise we wonHt do !any !ore tools; itHll 8e !ostly #ode and synta$ @or a while. But; weHll also ha7e a @ew tools we #an use to really see whatHs -oin- on and -et a -ood understandin- o@ #o!!on !istakes and "ro8le!s. @aster and hel" you @ind all

..1 Installing 3algrind


=ou cou$d i!sta$$ &alg$ind with the pac'age a!ager for &our .)# but I wa!t &ou to $ear! to i!sta$$ thi!gs fro source. %his i!vo$ves the fo$$owi!g process4 1ownload a sour#e ar#hi7e @ile to -et the sour#e. ,n"a#k the ar#hi7e to e$tra#t the @iles onto your #o!"uter. Run .'con%igu$e to setu" 8uild #on@i-urations. Run make to !ake it 8uild; 9ust like youH7e 8een doin-. Run sudo make install to install it onto your #o!"uter. @ere/s a script of e doi!g this ver& process# which I wa!t &ou to tr& to rep$icate4

1. 2.
(. ). ..

Source 1*: ex4.sh 1 # () *o+nload it ,use +get i% -ou don.t ave cu$l) 2 curl -> -ttp&//valgrind.org/downloads/valgrind-*.;.1.tar.b=6
( ) . 0 2 3 4 10 11 12 1( 1) 1. 10

# use md/sum to make su$e it matc es t e one on t e site md9sum valgrind-*.;.1.tar.b=6 # 0) 1npack it. tar -x?v( valgrind-*.;.1.tar.b=6 # cd into t e ne+l- c$eated di$ecto$cd valgrind-*.;.1 # #) con%igu$e it ./con(igure # 2) make it

12 13 14 20

make # /) install it ,need $oot) sudo make install

6o$$ow this# but obvious$& update it for !ew Aa$gri!d versio!s. If it does!/t bui$d the! tr& diggi!g i!to wh& as we$$.

..2 -sing 3algrind


?si!g &alg$ind is eas&# &ou 5ust ru! valgrind t-eprogram a!d it ru!s &our progra # the! pri!ts out a$$ the errors &our progra ade whi$e it was ru!!i!g. I! this e7ercise we/$$ brea' dow! o!e of the error outputs a!d &ou ca! get a! i!sta!t crash course i! +Aa$gri!d he$$+. %he! we/$$ fi7 the progra . 6irst# here/s a purposefu$$& bro'e! versio! of the ex#.c code for &ou to bui$d# !ow ca$$ed ex$.c. 6or practice# t&pe it i! agai!4
Source 1,: ex4.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10 11 12 1( 1)

'3 4a$ning5 6 is p$og$am is +$ong on pu$pose. 3' int main() { int age = 10; int -eig-t; print(("' am 2d years old.3n"); print(("' am 2d inc-es tall.3n", -eig-t); return 0; }

=ou/$$ see it/s the sa e e7cept I/ve ade two c$assic 1. +H7e @ailed to initiali<e the eig t 7aria8le. 2. +H7e @or-ot to -i7e the @irst p$int% the age 7aria8le.

ista'es4

..( What ou &hould &ee


-ow we wi$$ bui$d this 5ust $i'e !or a$# but i!stead of ru!!i!g it direct$&# we/$$ ru! it with &alg$indDsee )ource4 +,ui$di!g a!d ru!!i!g e74.c with Aa$gri!d+E4
Source 1.: *uilding and running ex4.c (ith 5algrind 1$ make ex0 2cc -%all -g ex0.c -o ex0

(ex0.c& 'n (unction )main)& )ex0.c&14& warning& too (ew arguments (or (ormat .ex0.c&5& warning& unused variable )age) 0ex0.c&11& warning& )-eig-t) is used uninitiali=ed in t-is (unction 2$ valgrind ./ex0 3$$*486$$ /emc-eck< a memory error detector 4$$*486$$ Copyrig-t @CA 6446-6414< and "BC "D )d< by Eulian #eward et al . 10$$*486$$ Csing Falgrind-*.;.4.#FB-Gebian and ibFHI7 rerun wit- -- (or copyrig-t in(o 11$$*486$$ Command& ./ex0 12$$*486$$ 1(' am -1;5590*6 years old. 1)$$*486$$ Cse o( uninitialised value o( si=e 8 1.$$*486$$ at 4x0H5*4HJ& KitoaKword @Kitoa.c&1:9A 10$$*486$$ by 4x0H50*G8& v(print( @v(print(.c&1;1*A 12$$*486$$ by 4x0H5H;F:& print( @print(.c&*9A 13$$*486$$ by 4x04496J& main @ex0.c&11A 14$$*486$$ 20$$*486$$ Conditional ?ump or move depends on uninitialised value@sA 21$$*486$$ at 4x0H5*4F9& KitoaKword @Kitoa.c&1:9A 22$$*486$$ by 4x0H50*G8& v(print( @v(print(.c&1;1*A 2($$*486$$ by 4x0H5H;F:& print( @print(.c&*9A 2)$$*486$$ by 4x04496J& main @ex0.c&11A 2.$$*486$$ 20$$*486$$ Conditional ?ump or move depends on uninitialised value@sA 22$$*486$$ at 4x0H5;**J& v(print( @v(print(.c&1;1*A 23$$*486$$ by 4x0H5H;F:& print( @print(.c&*9A 24$$*486$$ by 4x04496J& main @ex0.c&11A (0$$*486$$ (1$$*486$$ Conditional ?ump or move depends on uninitialised value@sA (2$$*486$$ at 4x0H500C;& v(print( @v(print(.c&1;1*A (($$*486$$ by 4x0H5H;F:& print( @print(.c&*9A ()$$*486$$ by 4x04496J& main @ex0.c&11A (.$$*486$$ (0' am 4 inc-es tall. (2$$*486$$ (3$$*486$$ HH!D #C//!LM& (4$$*486$$ in use at exit& 4 bytes in 4 blocks )0$$*486$$ total -eap usage& 4 allocs< 4 (rees< 4 bytes allocated )1$$*486$$ )2$$*486$$ !ll -eap blocks were (reed -- no leaks are possible )($$*486$$ ))$$*486$$ For counts o( detected and suppressed errors< rerun wit-& -v ).$$*486$$ Cse --track-origins$yes to see w-ere uninitialised values com e (rom )0$$*486$$ HLL>L #C//!LM& 0 errors (rom 0 contexts @suppressed& 0 (rom 0 A )2$

%ote ': Ubuntu6Debian 5algrind 7roblems +@ you run 7al-rind and it says so!ethin- like by 4x0496116& @below mainA @libcstart.c&66;A instead o@ a line nu!8er in main.c then add run your 7al-rind #o!!and like this valgrind --track-origins$yes ./ex0 to !ake it work. >or so!e reason the 1e8ian or ,8untu 7ersion o@ valg$ind does this 8ut not other 7ersions.

%his o!e is huge because &alg$ind is te$$i!g &ou e7act$& where ever& prob$e i! &our progra is. )tarti!g at the top here/s what &ou/re readi!g# $i!e b& $i!e D$i!e !u bers are o! the $eft so &ou ca! fo$$owE4 1 You do the usual make ex0 and that 8uilds it. %ake sure the cc #o!!and you see is the sa!e and has the -g o"tion or your &alg$ind out"ut wonHt ha7e line nu!8ers. 6, 6oti#e that the #o!"iler is also yellin- at you a8out this sour#e @ile and it warns you that you ha7e Itoo @ew ar-u!ents @or @or!atI. ThatHs where you @or-ot to in#lude the age 7aria8le. . Then you run your "ro-ra! usin- valgrind ./ex0. 0 Then &alg$ind -oes #ra<y and yells at you @orD 1'610 &n line main @ex0.c&11A Eread as Iin the !ain @un#tion in @ile e$).# at line 11F you ha7e I,se o@ uninitialised 7alue o@ si<e 3I. You @ind this 8y lookin- at the error; then you see whatHs #alled a Ista#k tra#eI ri-ht under that. The line to look at @irst Ee$).#D11F is the 8otto! one; and i@ you donHt see whatHs -oin- wron- then you -o u"; so youHd try "rint@.#D(.. Ty"i#ally itHs the 8otto! !ost line that !atters Ein this #ase; on line 13F. 06 ' 6e$t error is yet another one on line e$).#D11 in the !ain @un#tion. &alg$ind hates this line. This error says that so!e kind o@ i@A

state!ent or whileAloo" ha""ened that was 8ased on an uninitiali<ed 7aria8le; in this #ase hei-ht. *6!* The re!ainin- errors are !ore o@ the sa!e 8e#ause the 7aria8le kee"s -ettin- used. !.6', >inally the "ro-ra! e$its and &alg$ind tells you a su!!ary o@ how 8ad your "ro-ra! is. %hat is quite a $ot of i!for atio! to ta'e i!# but here/s how &ou dea$ with it4 1. Whene7er you run your #ode and -et it workin-; rerun it under &alg$ind to #he#k it. 2. >or ea#h error that you -et; -o to the sour#eDline indi#ated and @i$ it. You !ay ha7e to sear#h online @or the error !essa-e to @i-ure out what it !eans. (. &n#e your "ro-ra! is I/al-rind "ureI then it should 8e -ood; and you ha7e "ro8a8ly learned so!ethin- a8out how you write #ode. I! this e7ercise I/ !ot e7pecti!g &ou to fu$$& grasp &alg$ind right awa&# but i!stead get it i!sta$$ed a!d $ear! how to use it rea$ quic' so we ca! app$& it to a$$ the $ater e7ercises.

..) '(tra Credit


>i$ this "ro-ra! usin- &alg$ind and the #o!"iler as your -uide. 2. Read u" on &alg$ind on the internet. (. 1ownload other so@tware and 8uild it 8y hand. Try so!ethin- you already use 8ut ne7er 8uilt @or yoursel@. ). Look at how the &alg$ind sour#e @iles are laid out in the sour#e dire#tory and read its %ake@ile. 1onHt worry; none o@ that !akes sense to !e either.
1.

ha"ter 0
'(ercise 4: The &tructure Of A C Program

=ou '!ow how to use p$int% a!d have a coup$e basic too$s at &our disposa$# so $et/s brea' dow! a si p$e " progra $i!e8b&8 $i!e so &ou '!ow how o!e is structured. I! this progra &ou/re goi!g to t&pe i! a few ore thi!gs that &ou/re u!fa i$iar with# a!d I/ goi!g to $ight$& brea' the dow!. %he! i! the !e7t few e7ercises we/re goi!g to wor' with these co!cepts.
Source 10: ex8.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10 11 12

'3 6 is is a comment. 3' int main(int argc, char *argv[]) { int distance = 100; '' t is is also a comment print(("Mou are 2d miles away.3n", distance); return 0; }

%&pe this code i!# a'e it ru!# a!d a'e sure &ou get no 5algrind errors. =ou probab$& wo!/t but get i! the habit of chec'i!g it.

0.1 What ou &hould &ee


%his has prett& bori!g output# but the poi!t of this e7ercise is to a!a$&0e the code4
Source 12: ex8 output 1$ make ex9 2cc -%all -g ex9.c -o ex9 ($ ./ex9 )Mou are 144 miles away. .$

0.2 #rea$ing It Do!n


%here/s a few features of the " $a!guage i! this code that &ou ight have o!$& s$ight$& figured out whi$e &ou were t&pi!g code. *et/s brea' this dow! $i!e8b&8$i!e quic'$&# a!d the! we ca! do e7ercises to u!dersta!d each part better4 ex*Bc:1

An include and it is the way to i!"ort the #ontents o@ one @ile into this sour#e @ile. has a #on7ention o@ usin- .h e$tensions @or IheaderI @iles; whi#h then #ontain lists o@ @un#tions you want to use in your "ro-ra!. ex*Bc:! This is a !ultiAline comment and you #ould "ut as !any lines o@ te$t 8etween the /1 and #losin- 1/#hara#ters as you want. ex*Bc:' A !ore #o!"le$ 7ersion o@ the main %unction youH7e 8een usin8lindly so @ar. How "ro-ra!s work is the o"eratin- syste! loads your "ro-ra!; and then runs the @un#tion na!ed main. >or the @un#tion to 8e totally #o!"lete it needs to return an int and take two "ara!eters; an int @or the ar-u!ent #ount; and an array o@ c a$ 3 strin-s @or the ar-u!ents. 1id that 9ust @ly o7er your head? 1o not worry; weHll #o7er this soon. ex*Bc:* To start the 8ody o@ any @un#tion you write a N #hara#ter that indi#ates the 8e-innin- o@ a I8lo#kI. +n 5ython you 9ust did a & and indented. +n other lan-ua-es you !i-ht ha7e a 7egin or doword to start. ex*Bc:, A 7aria8le de#laration and assi-n!ent at the sa!e ti!e. This is how you #reate a 7aria8le; with the synta$ type name $ value7. +n state!ents Ee$#e"t @or lo-i#F end in a )7) Ese!i#olonF #hara#ter. ex*Bc:0 Another kind o@ #o!!ent; and it works like 5ython or Ru8y #o!!ents where it starts at the //and -oes until the end o@ the line. ex*Bc:2 A #all to your old @riend p$int%. Like in !any lan-ua-es @un#tion #alls work with the synta$name@arg1< arg6A7 and #an ha7e no ar-u!ents; or any nu!8er. The p$int% @un#tion is a#tually kind o@ weird and #an take !ulti"le ar-u!ents. WeHll see that later. ex*Bc:11

A return @ro! the !ain @un#tion; whi#h -i7es the &S your e$it 7alue. You !ay not 8e @a!iliar with how ,ni$ so@tware uses return #odes; so weHll #o7er that as well. ex*Bc:1 >inally; we end the !ain @un#tion with a #losin- 8ra#e O #hara#ter and thatHs the end o@ the "ro-ra!. %here/s a $ot of i!for atio! i! this brea'8dow!# so stud& it $i!e8 b&8$i!e a!d a'e sure &ou at $east have a $itt$e grasp of what/s goi!g o!. =ou wo!/t '!ow ever&thi!g# but &ou ca! probab$& guess before we co!ti!ue.

0.( '(tra Credit


1. >or ea#h line; write out the sy!8ols you donHt understand and see i@ you #an -uess what they !ean. Write a little #hart on "a"er with your -uess that you #an use to #he#k later and see i@ you -et it ri-ht. 2. :o 8a#k to the sour#e #ode @ro! the "re7ious e$er#ises and do a si!ilar 8reakAdown to see i@ youHre -ettin- it. Write down what you donHt know and #anHt e$"lain to yoursel@.

ha"ter 2
'(ercise 5: Ty%es Of 3aria6les
=ou shou$d be getti!g a grasp of how a si p$e " progra is structured# so $et/s do the !e7t si p$est thi!g which is a'i!g so e variab$es of differe!t t&pes4
Source 0: ex9.c 1 #include <stdio. !
2 ( ) . 0 2 3 4

int main(int argc, char *argv[]) { int distance = 100; fl"at power = 2.#$%f; !"u&le superKpower = %'7().$%#2; char initial = )!); char (irstKname[] = "Ped";

10 11 12 1( 1) 1. 10 12 13 14 20 21 22

char lastKname[] = "#-aw"; print(("Mou are 2d miles away.3n", distance); print(("Mou -ave 2( levels o( power.3n", power); print(("Mou -ave 2( awesome super powers.3n", superKpower); print(("' -ave an initial 2c.3n", initial); print(("' -ave a (irst name 2s.3n", (irstKname); print(("' -ave a last name 2s.3n", lastKname); print(("/y w-ole name is 2s 2c. 2s.3n", (irstKname, initial, lastKname); return 0; }

I! this progra we/re dec$ari!g variab$es of differe!t t&pes a!d the! pri!ti!g the with differe!tp$int% for at stri!gs.

2.1 What ou &hould &ee


=our output shou$d $oo' $i'e i!e# a!d &ou ca! start to see how the for at stri!gs for " are si i$ar to 9&tho! a!d other $a!guages. %he&/ve bee! arou!d for a $o!g ti e.
Source 1: ex9 output 1$ make ex; 2cc -%all -g ex;.c -o ex; ($ ./ex; )Mou are 144 miles away. .Mou -ave 6.*09444 levels o( power. 0Mou -ave 9;58:.09*644 awesome super powers. 2' -ave an initial !. 3' -ave a (irst name Ped. 4' -ave a last name #-aw. 10/y w-ole name is Ped !. #-aw. 11$

1hat &ou ca! see is we have a set of +t&pes+# which are wa&s of te$$i!g the " co pi$er what each variab$e shou$d represe!t# a!d the! for at stri!gs to atch differe!t t&pes. @ere/s the brea'dow! of how the& atch up4 Inte)ers You de#lare +nte-ers with the int keyword; and "rint the! with 2d. (loatin) Point 1e#lared with %loat or dou7le de"endin- on how 8i- they need to 8e Edou8le is 8i--erF; and "rinted with 2(.

Character 1e#lared with c a$; written with a ) Esin-leACuoteF #hara#ter around the #har; and then "rinted with 2c. Strin) C-rra$ of CharactersD 1e#lared with c-ar nameQR; written with " #hara#ters; and "rinted with 2s. =ou/$$ !otice that " a'es a disti!ctio! betwee! si!g$e8quote for c a$ a!d doub$e8quote for c a$89 or stri!gs.
%ote *: C 'ype :hort+;and #or %nglish When talkin- a8out ty"es; + will ty"i#ally write in *n-lish #harLM instead o@ the whole #har #ode; 9ust a si!"ler way to talk a8out ty"es when writin- *n-lish. S&%*6A%*LM. This is not 7alid

2.2 Ho! To #rea$ It


=ou ca! easi$& brea' this progra b& passi!g the wro!g thi!g to the pri!tf state e!ts. 6or e7a p$e# if &ou ta'e the $i!e that pri!ts & !a e# but put the initial variab$e before the %i$st:namei! the argu e!ts# &ou/$$ get a bug. ;a'e that cha!ge a!d the co pi$er wi$$ &e$$ at &ou# the! whe! &ou ru! it &ou ight get a +)eg e!tatio! fau$t+ $i'e I did4
Source : ex9 explosion 1$ make ex; 2cc -%all -g ex;.c -o ex; (ex;.c& 'n (unction )main)& )ex;.c&1:& warning& (ormat )2s) expects type )c-ar 1)< but argument 6 -a s type )int) .ex;.c&1:& warning& (ormat )2c) expects type )int)< but argument * -as t ype )c-ar 1) 0$ ./ex; 2Mou are 144 miles away. 3Mou -ave 6.*09444 levels o( power. 4Mou -ave 9;58:.09*169 awesome super powers. 10' -ave an initial !. 11' -ave a (irst name Ped. 12' -ave a last name #-aw. 1(#egmentation (ault 1)$

:u! this cha!ge u!der Aa$gri!d too to see what it te$$s &ou about the error +I!va$id read of si0e 1+.

2.( '(tra Credit

o!e u" with other ways to 8reak this #ode 8y #han-in- the p$int%; then @i$ the!. 2. :o sear#h @or I"rint@ @or!atsI and try usin- a @ew o@ the !ore e$oti# ones. (. Resear#h how !any di@@erent ways you #an write a nu!8er. Try o#tal; he$ade#i!al; and others you #an @ind. ). Try "rintin- an e!"ty strin- thatHs 9ust "".
1.

ha"ter 3
'(ercise 7: More 3aria6les8 &ome Math
*et/s get fa i$iar with ore thi!gs &ou ca! do with variab$es b& dec$ari!g various ints# %loats# c a$s# a!d dou7les. 1e/$$ the! use these i! various ath e7pressio!s so &ou get i!troduced to "/s basic ath.
Source !: ex<.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10 11 12 1( 1) 1. 10 12 13 14 20 21 22 2( 2) 2. 20 22

int main(int argc, char *argv[]) { int bugs = 100; !"u&le bugKrate = 1.2; print(("Mou -ave 2d bugs at t-e imaginary rate o( 2(.3n", bugs, bugKrate); l"n* universeKo(Kde(ects = 1+ * 102$+ * 102$+ * 102$+; print(("S-e entire universe -as 2ld bugs.3n", universeKo(Kde(ects); !"u&le expectedKbugs = bugs * bugKrate; print(("Mou are expected to -ave 2( bugs.3n", expectedKbugs); !"u&le partKo(Kuniverse = expectedKbugs , universeKo(Kde(ects; print(("S-at is only a 2e portion o( t-e universe.3n", partKo(Kuniverse); '' t is makes no sense; <ust a demo o% somet ing +ei$d char nulKbyte = )34); int careKpercentage = bugs * nulKbyte; print(("%-ic- means you s-ould care 2d22.3n", careKpercentage);

23 24 (0

return 0; }

@ere/s what/s goi!g o! i! this $itt$e bit of !o!se!se4 ex.Bc:16' The usual start o@ a "ro-ra!. ex.Bc:*6, 1e#lare an int and dou7le @or so!e @ake 8u- data. ex.Bc:062 5rint out those two; so nothin- new here. ex.Bc:11 1e#lare a hu-e nu!8er usin- a new ty"e long @or storin- 8i- nu!8ers. ex.Bc:1 61! 5rint out that nu!8er usin- 2ld whi#h adds a !odi@ier to the usual 2d. Addin- HlH Ethe letter ellF !eans I"rint this as a lon- de#i!alI. ex.Bc:1*61. Just !ore !ath and "rintin-. ex.Bc:126 1 ra@t u" a de"i#tion o@ your 8u- rate #o!"ared to the 8u-s in the uni7erse; whi#h is a #o!"letely ina##urate #al#ulation. +tHs so s!all thou-h that we ha7e to use 2e to "rint it in s#ienti@i# notation. ex.Bc: ' %ake a #hara#ter; with a s"e#ial synta$ )34) whi#h #reates a Hnul 8yteH #hara#ter. This is e@@e#ti7ely the nu!8er 0. ex.Bc: * %ulti"ly 8u-s 8y this #hara#ter; whi#h "rodu#es 0 @or how !u#h you should #are. This de!onstrates an u-ly ha#k you @ind so!eti!es. ex.Bc: ,6 . 5rint that out; and noti#e +H7e -ot a 22 Etwo "er#ent #harsF so + #an "rint a HKH E"er#entF #hara#ter. ex.Bc: 06!0 The end o@ the main @un#tion. %his bit of source is e!tire$& 5ust a! e7ercise# a!d de o!strates how so e ath wor's. 3t the e!d# it a$so

de o!strates so ethi!g &ou see i! "# but !ot i! a!& other $a!guages. %o "# a +character+ is 5ust a! i!teger. It/s a rea$$& s a$$ i!teger# but that/s a$$ it is. %his ea!s &ou ca! do ath o! the # a!d a $ot of software does 5ust that# for good or bad. %his $ast bit is &our first g$a!ce at how " gives &ou direct access to the achi!e. 1e/$$ be e7p$ori!g that ore i! $ater e7ercises.

3.1 What ou &hould &ee


3s usua$# here/s what &ou shou$d see for the output4
Source ': ex< output 1$ make ex5 2cc -%all -g ex5.c -o ex5 ($ ./ex5 )Mou -ave 144 bugs at t-e imaginary rate o( 1.644444. .S-e entire universe -as 145*501860 bugs. 0Mou are expected to -ave 164.444444 bugs. 2S-at is only a 1.115985e-45 portion o( t-e universe. 3%-ic- means you s-ould care 42. 4$

3.2 Ho! To #rea$ It


3gai!# go through this a!d tr& brea'i!g the p$int% b& passi!g i! the wro!g argu e!ts. )ee what happe!s whe! &ou tr& to pri!t out that nul:7-te variab$e too with 2s vs. 2c. 1he! &ou brea' it# ru! it u!der &alg$ind to see what it sa&s about &our brea'i!g atte pts.

3.( '(tra Credit


1.

2.
(. ). ..

%ake the nu!8er you assi-n to unive$se:o%:de%ects 7arious si<es until you -et a warnin- @ro! the #o!"iler. What do these really hu-e nu!8ers a#tually "rint out? han-e long to unsigned long and try to @ind the nu!8er that !akes that one too 8i-. :o sear#h online to @ind out what unsigned does. Try to e$"lain to yoursel@ E8e@ore + do in the ne$t e$er#iseF why you #an !ulti"ly a c a$ and anint.

Chapter 2
'(ercise 9: &i:es And Arrays
I! the $ast e7ercise &ou did ath# but with a )34) D!u$E character. %his a& be odd co i!g fro other $a!guages# si!ce the& tr& to treat +stri!gs+ a!d +b&te arra&s+ as differe!t beasts. " however treats stri!gs as 5ust arra&s of b&tes# a!d it/s o!$& the differe!t pri!ti!g fu!ctio!s that '!ow there/s a differe!ce. ,efore I ca! rea$$& e7p$ai! the sig!ifica!ce of this# I have to i!troduce a few ore co!cepts4 si=eo%a!d arra&s. @ere/s the code we/$$ be ta$'i!g about4
Source *: ex=.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10 11 12 1( 1) 1. 10 12 13 14 20 21 22 2( 2) 2. 20 22 23 24 (0

int main(int argc, char *argv[]) { int areas[] = {10, 12, 1#, 1$, 20}; char name[] = "Ped"; char (ullKname[] = { )P), )e), )d), ) ), )!), ).), ) ), )#), )-), )a), )w), )34) }; '' 4AR>?>G5 @n some s-stems -ou ma- ave to c ange t e '' Ald in t is code to a Au since it +ill use unsigned ints print(("S-e si=e o( an int& 2ld3n", i-e"f(int)); print(("S-e si=e o( areas @intQRA& 2ld3n", i-e"f(areas)); print(("S-e number o( ints in areas& 2ld3n", i-e"f(areas) , i-e"f(int)); print(("S-e (irst area is 2d< t-e 6nd 2d.3n", areas[0], areas[1]); print(("S-e si=e o( a c-ar& 2ld3n", i-e"f(char)); print(("S-e si=e o( name @c-arQRA& 2ld3n", i-e"f(name)); print(("S-e number o( c-ars& 2ld3n", i-e"f(name) , i-e"f(char)); print(("S-e si=e o( (ullKname @c-arQRA& 2ld3n", i-e"f((ullKname));

(1 (2 (( () (. (0 (2 (3

print(("S-e number o( c-ars& 2ld3n", i-e"f((ullKname) , i-e"f(char)); print(("name$3"2s3" and (ullKname$3"2s3"3n", name, (ullKname); return 0; }

1. 2. (.

).
..

I! this code we create a few arra&s with differe!t data t&pes i! the . ,ecause arra&s of data are so ce!tra$ to how " wor's# there/s a huge !u ber of wa&s to create the . 6or !ow# 5ust use the s&!ta7 type nameQR $ Ninitiali=erO7 a!d we/$$ e7p$ore ore. 1hat this s&!ta7 ea!s is# +I wa!t a! arra& of t&pe that is i!itia$i0ed to ...+ 1he! " sees this it does the fo$$owi!g4 Look at the ty"e; in this @irst #ase itHs int. Look at the QR and see that thereHs no len-th -i7en. Look at the initiali<er; N14< 16< 1*< 10< 64O and @i-ure out that you want those . ints in your array. reate a "ie#e o@ !e!ory in the #o!"uter; that #an hold . inte-ers one a@ter another. Take the na!e you want; a$eas and assi-n it this lo#ation. I! the case of a$eas it/s creati!g a! arra& of 5 i!ts that co!tai! those !u bers. 1he! it gets toc-ar nameQR $ "Ped"7 it/s doi!g the sa e thi!g# e7cept it/s creati!g a! arra& of 3 chars a!d assig!i!g that to name. %he fi!a$ arra& we a'e is %ull:name# but we use the a!!o&i!g s&!ta7 of spe$$i!g it out# o!e character at a ti e. %o "# name a!d %ull:name are ide!tica$ ethods of creati!g a char arra&. %he rest of the fi$e# we/re usi!g a 'e&word ca$$ed si=eo% to as' " how big thi!gs are i! bytes. " is a$$ about the si0e a!d $ocatio! of pieces of e or& a!d what &ou do with the . %o he$p &ou 'eep that straight# it gives &ou si=eo% so &ou ca! as' how big so ethi!g is before &ou wor' with it. %his is where stuff gets tric'&# so first $et/s ru! this a!d the! e7p$ai! further.

2B1 What ou &hould &ee


Source ,: ex= output 1$ make ex8 2cc -%all -g ex8.c -o ex8 ($ ./ex8 )S-e si=e o( an int& 0 .S-e si=e o( areas @intQRA& 64 0S-e number o( ints in areas& 9 2S-e (irst area is 14< t-e 6nd 16. 3S-e si=e o( a c-ar& 1 4S-e si=e o( name @c-arQRA& 0 10S-e number o( c-ars& 0 11S-e si=e o( (ullKname @c-arQRA& 16 12S-e number o( c-ars& 16 1(name$"Ped" and (ullKname$"Ped !. #-aw" 1)$

-ow &ou see the output of these differe!t p$int% ca$$s a!d start to get a g$i pse of what " is doi!g. =our output cou$d actua$$& be tota$$& differe!t fro i!e# si!ce &our co puter ight have differe!t si0e i!tegers. I/$$ go through & output4 * %y #o!"uter thinks an int is ) 8ytes in si<e. Your #o!"uter !i-ht use a di@@erent si<e i@ itHs a (2A8it 7s. 0)A8it. , The a$eas array has . inte-ers in it; so it !akes sense that !y #o!"uter reCuires 20 8ytes to store it. . +@ we di7ide the si<e o@ a$eas 8y si<e o@ an int then we -et . ele!ents. Lookin- at the #ode; this !at#hes what we "ut in the initiali<er. 0 We then did an array a##ess to -et areasQ4R and areasQ1R whi#h !eans is I<ero inde$edI like 5ython and Ru8y. 2611 We re"eat this @or the name array; 8ut noti#e so!ethin- odd a8out the si<e o@ the array? +t says itHs 4 8ytes lon-; 8ut we only ty"ed IZedI @or ( #hara#ters. WhereHs the )th one #o!in- @ro!? 1 61!

We do the sa!e thin- with %ull:name and noti#e it -ets this #orre#t. 1! >inally we 9ust "rint out the name and %ull:name to "ro7e that they a#tually are Istrin-sI a##ordin- to "rint@. ;a'e sure &ou ca! go through a!d see how these output $i!es atch what was created. 1e/$$ be bui$di!g o! this a!d e7p$ori!g ore about arra&s a!d storage !e7t.

2B Ho! To #rea$ It
,rea'i!g this progra is fair$& eas&. %r& so e of these4 2. :et rid o@ the )34) at the end o@ %ull:name and reArun it. Run it under /al-rind too. 6ow; !o7e the de@inition o@ %ull:name to the to" o@ main 8e@ore a$eas. Try runnin- it under /al-rind a @ew ti!es and see i@ you -et so!e new errors. +n so!e #ases; you !i-ht still -et lu#ky and not #at#h any errors. 3. han-e it so that instead o@ areasQ4R you try to "rint areasQ14R and see what /al-rind thinks o@ that. 4. Try other 7ersions o@ these; doin- it to name and %ull:name too.

2B! '(tra Credit


Try assi-nin- to ele!ents in the a$eas array with areasQ4R $ 1447 and si!ilar. 2. Try assi-nin- to ele!ents o@ name and %ull:name. 3. Try settin- one ele!ent o@ a$eas to a #hara#ter @ro! name. 4. :o sear#h online @or the di@@erent si<es used @or inte-ers on di@@erent 5,s.
0.

Chapter 10
'(ercise ;: Arrays And &trings
I! the $ast e7ercise &ou we!t through a! i!troductio! to creati!g basic arra&s a!d how the& ap to stri!gs. I! this

e7ercise we/$$ ore co p$ete$& show the si i$arit& betwee! arra&s a!d stri!gs# a!d get i!to ore about e or& $a&outs. %his e7ercise shows &ou that " stores its stri!gs si p$& as a! arra& of b&tes# ter i!ated with the)34) D!u$E b&te. =ou probab$& c$ued i!to this i! the $ast e7ercise si!ce we did it a!ua$$&. @ere/s how we do it i! a!other wa& to a'e it eve! ore c$ear b& co pari!g it to a! arra& of !u bers4
Source .: ex>.c 1 #include <stdio. !
2 ( ) . 0 2 3 4 10 11 12 1( 1) 1. 10 12 13 14 20 21 22 2( 2) 2. 20 22 23 24 (0 (1 (2 (( () (. (0

int main(int argc, char *argv[]) { int numbers[$] = {0}; char name[$] = {)a)}; '' %i$st; p$int t em out $a+ print(("numbers& 2d 2d 2d 2d3n", numbers[0], numbers[1], numbers[2], numbers[#]); print(("name eac-& 2c 2c 2c 2c3n", name[0], name[1], name[2], name[#]); print(("name& 2s3n", name); '' setup t numbers[0] numbers[1] numbers[2] numbers[#] e = = = = num7e$s 1; 2; #; $;

'' setup t e name name[0] = )P); name[1] = )e); name[2] = )d); name[#] = )34); '' t en p$int t em out initiali=ed print(("numbers& 2d 2d 2d 2d3n", numbers[0], numbers[1], numbers[2], numbers[#]); print(("name eac-& 2c 2c 2c 2c3n",

(2 (3 (4 )0 )1 )2 )( )) ). )0 )2 )3 )4 .0 .1 .2 .(

name[0], name[1], name[2], name[#]); '' p$int t e name like a st$ing print(("name& 2s3n", name); '' anot e$ +a- to use name char *anot-er = "Ped"; print(("anot-er& 2s3n", anot-er); print(("anot-er eac-& 2c 2c 2c 2c3n", anot-er[0], anot-er[1], anot-er[2], anot-er[#]); return 0; }

I! this code# we setup so e arra&s the tedious wa&# b& assig!i!g a va$ue to each e$e e!t. I!num7e$s we are setti!g up !u bers# but i! name we/re actua$$& bui$di!g a stri!g a!ua$$&.

10B1 What ou &hould &ee


1he! &ou ru! this code &ou shou$d see first the arra&s pri!ted with their co!te!ts i!itia$i0ed to 0ero# the! i! its i!itia$i0ed for 4
Source 0: ex> output 1$ make ex: 2cc -%all -g ($ ./ex: )numbers& 4 4 4 .name eac-& a 0name& a 2numbers& 1 6 * 3name eac-& P e 4name& Ped 10anot-er& Ped 11anot-er eac-& 12$
ex:.c 4 -o ex:

0 d

P e d

Potrebbero piacerti anche