by Dan Gookin C A L L - I N - O N E D E S K R E F E R E N C E FOR DUMmIES ‰ 01_570692 ffirs.qxd 7/30/04 11:08 AM Page iii
01_570692 ffirs.qxd 7/30/04 11:08 AM Page ii
C A L L - I N - O N E D E S K R E F E R E N C E FOR DUMmIES ‰ 01_570692 ffirs.qxd 7/30/04 11:08 AM Page i
01_570692 ffirs.qxd 7/30/04 11:08 AM Page ii
by Dan Gookin C A L L - I N - O N E D E S K R E F E R E N C E FOR DUMmIES ‰ 01_570692 ffirs.qxd 7/30/04 11:08 AM Page iii
C All-in-One Desk Reference For Dummies® Published by Wiley Publishing, Inc. 111 River Street Hoboken, NJ 07030-5774 Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis- sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, e-mail: brandreview@ wiley.com. Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPE- TENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services or to obtain technical support, please con- tact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2004102339 ISBN: 0-7645-7069-2 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1O/RX/QY/QU/IN 01_570692 ffirs.qxd 7/30/04 11:08 AM Page iv
About the Author Dan Gookin has been writing about technology for 20 years. He has con- tributed articles to numerous high-tech magazines and written more than 90 books about personal computing technology, many of them accurate. He combines his love of writing with his interest in technology to create books that are informative and entertaining, but not boring. Having sold more than 14 million titles translated into more than 30 languages, Dan can attest that his method of crafting computer tomes does seem to work. Perhaps Dan’s most famous title is the original DOS For Dummies, published in 1991. It became the world’s fastest-selling computer book, at one time moving more copies per week than the New York Times number-one best seller (although, because it’s a reference book, it could not be listed on the NYT best seller list). That book spawned the entire line of For Dummies books, which remains a publishing phenomenon to this day. Dan’s most recent titles include PCs For Dummies, 9th Edition; Buying a Computer For Dummies, 2005 Edition; Troubleshooting Your PC For Dummies; Dan Gookin’s Naked Windows XP; and Dan Gookin’s Naked Office. He publishes a free weekly computer newsletter, “Weekly Wambooli Salad,” and also main- tains the vast and helpful Web site www.wambooli.com. Dan holds a degree in communications and visual arts from the University of California, San Diego. He lives in the Pacific Northwest, where he enjoys spending time with his four boys in the gentle woods of Idaho. 01_570692 ffirs.qxd 7/30/04 11:08 AM Page v
Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/. Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development Project Editor: Rebecca Whitney Acquisitions Editor: Greg Croy Technical Editor: Greg Guntle Editorial Manager: Carol Sheehan Editorial Assistant: Amanda M. Foxworth Cartoons: Rich Tennant, www.the5thwave.com Composition Project Coordinator: Maridee Ennis Layout and Graphics: Karl Brandt, Denny Hager, Joyce Haughey, Stephanie D. Jumper, Michael Kruzil, Melanee Prendergast, Jacque Roth, Julie Trippetti, Mary Gillot Virgin Proofreaders: Arielle Carole Mennelle, Dwight Ramsey, Brian H. Walls Indexer: Infodex Indexing Services Inc. Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Editorial Director Mary C. Corder, Editorial Director Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services 01_570692 ffirs.qxd 7/30/04 11:08 AM Page vi
Contents at a Glance Introduction ................................................................1 Book I: Hello, C ............................................................7 Chapter 1: Your Basic C Program ....................................................................................9 Chapter 2: How It All Works ...........................................................................................19 Chapter 3: More Basics, Comments, and Errors .........................................................33 Chapter 4: Introducing Numbers and Variables ..........................................................47 Chapter 5: More Variables and Basic I/O ......................................................................61 Chapter 6: Decision Time ...............................................................................................79 Chapter 7: Looping ..........................................................................................................89 Chapter 8: Using Constants ..........................................................................................101 Chapter 9: Mysterious Math ........................................................................................109 Chapter 10: It’s Only Logical ........................................................................................123 Book II: Middle C .....................................................133 Chapter 1: Variables from Beyond Infinity .................................................................135 Chapter 2: The Madness of Printf( ) ............................................................................149 Chapter 3: Maniacal Math Functions ..........................................................................165 Chapter 4: Not Truly Random ......................................................................................181 Chapter 5: While Going Loopy .....................................................................................193 Chapter 6: More Decision Making ...............................................................................205 Chapter 7: The Goto Chapter .......................................................................................217 Book III: Above C Level.............................................221 Chapter 1: Asking for Arrays ........................................................................................223 Chapter 2: I Sing of Strings ...........................................................................................243 Chapter 3: Messing with Characters ...........................................................................265 Chapter 4: Stinkin’ Structures ......................................................................................271 Chapter 5: Creating Your Own Functions ...................................................................293 Chapter 6: Quitting Before You’re Done .....................................................................319 Chapter 7: More Variable Nonsense ............................................................................329 02_570692 ftoc.qxd 7/30/04 9:47 AM Page vii
Book IV: Advanced C ................................................347 Chapter 1: Introduction to Evil Pointers ....................................................................349 Chapter 2: Getting to the *Point ..................................................................................373 Chapter 3: Binary Bits ...................................................................................................381 Chapter 4: The Myth of the Array ...............................................................................403 Chapter 5: Pointers and Strings ...................................................................................417 Chapter 6: Crazy Arrays of Pointers ...........................................................................429 Chapter 7: Functions and Pointers ..............................................................................451 Chapter 8: Structures, Pointers, and the Malloc Deity .............................................471 Chapter 9: Does Anyone Have the Time? ...................................................................485 Chapter 10: Building Big Programs .............................................................................497 Chapter 11: Help! ...........................................................................................................511 Book V: Disk Drive C.................................................521 Chapter 1: Just Your Standard I/O ...............................................................................523 Chapter 2: Interacting with the Command Line ........................................................537 Chapter 3: Hello, Disk! ...................................................................................................547 Chapter 4: More Formal File Writing and Reading ....................................................561 Chapter 5: Random Access Files .................................................................................575 Chapter 6: Folder Folderol ...........................................................................................585 Chapter 7: Under New File Management ....................................................................607 Book VI: The Joy of Linked Lists ................................615 Chapter 1: Why Linked Lists? ......................................................................................617 Chapter 2: Dawn of the Database ................................................................................629 Chapter 3: Storing a Linked List on Disk ....................................................................643 Chapter 4: The Nightmare of the Double-Linked List ...............................................655 Book VII: Appendixes ................................................667 Appendix A: The Stuff You Need to Know before Reading Everything Else in This Book ....................................................................................669 Appendix B: ASCII Table ...............................................................................................681 Appendix C: Answers to Exercises ..............................................................................685 Appendix D: C Language Keywords and Operators ..................................................763 Appendix E: C Language Variable Types ....................................................................767 Appendix F: Escape Sequences ...................................................................................769 Appendix G: Conversion Characters ...........................................................................771 Index .......................................................................773 02_570692 ftoc.qxd 7/30/04 9:47 AM Page viii
Table of Contents Introduction .................................................................1 Why Bother with C When C++ Is Obviously Blah-Blah-Blah? ....................1 About This Here Dummies Approach ...........................................................2 How This Book Works .....................................................................................3 Icons Used in This Book .................................................................................5 Final Thots .......................................................................................................5 Book I: Hello, C.............................................................7 Chapter 1: Your Basic C Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 The Section Where the Author Cannot Resist Describing the History of C ........................................................................9 Time to Program! ...........................................................................................11 The basic, simplest C program ..........................................................11 The main() function ...........................................................................12 Inside the main() function ................................................................13 “Am I done?” .........................................................................................13 Declaring main() as an int ...............................................................14 A little sprucing up ..............................................................................15 Finally, making main() do something ..............................................16 One more thing! ...................................................................................17 The C Skeleton ...............................................................................................18 Chapter 2: How It All Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 Your Computer Programming Bag of Tools ...............................................20 The C Programming Language ....................................................................20 Keywords ..............................................................................................20 Functions ..............................................................................................21 Operators .............................................................................................23 Variables and values ...........................................................................23 Other C language goodies ..................................................................24 Putting It Together in the Editor .................................................................24 Making a Program .........................................................................................25 The compiler ........................................................................................25 The object code file .............................................................................28 The linker .............................................................................................29 02_570692 ftoc.qxd 7/30/04 9:47 AM Page ix
C All-in-One Desk Reference For Dummiesx Chapter 3: More Basics, Comments, and Errors . . . . . . . . . . . . . . . . . .33 Simple “Hello” Programs ..............................................................................33 The STOP program ..............................................................................34 Reediting your source code ...............................................................34 Printing text with printf() ..............................................................35 Introducing the newline, \n ...............................................................35 Adding Comments, Remarks, and Suggestions .........................................36 /* C language comments */ ................................................................36 Using comments to disable code ......................................................38 Watch out for nested comments! ......................................................39 Fixing a double-quote problem ..........................................................41 Debugging ......................................................................................................42 Prepare to fail .......................................................................................43 Dealing with linker errors ...................................................................44 Run-time errors and bugs ...................................................................44 Error messages subtle and gross ......................................................45 Chapter 4: Introducing Numbers and Variables . . . . . . . . . . . . . . . . . .47 Going Numb with Numbers ..........................................................................47 The joys of integers .............................................................................48 Flying high with floating-point numbers ..........................................49 Introduction to Variables .............................................................................52 Creating variables ................................................................................52 Assigning values to variables ............................................................53 Using an int variable ...........................................................................54 Changing a variable’s contents ..........................................................55 Using a float variable ..........................................................................56 Using multiple variables .....................................................................56 Immediately declaring a variable’s value .........................................58 The Official Introduction to Basic Math Operators ..................................59 Chapter 5: More Variables and Basic I/O . . . . . . . . . . . . . . . . . . . . . . . .61 The Good Ol’ char Variable .........................................................................61 Presenting the single character .........................................................62 Single quotes are holy too ..................................................................63 Here a char, there a char, everywhere a char char ....................64 Displaying characters one at a time with putchar() ....................64 Using char as a tiny integer value ....................................................65 Getting Input from the Keyboard ................................................................68 Reading the keyboard one key at a time ..........................................68 The problem with getchar() ...........................................................69 Clearing the input stream ...................................................................71 Reading a chunk of text with gets() ...............................................72 How to input numeric values .............................................................74 Directly reading values with scanf() ..............................................75 Summary of Basic Text I/O Functions ........................................................77 02_570692 ftoc.qxd 7/30/04 9:47 AM Page x
Table of Contents xi Chapter 6: Decision Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79 Making Decisions with if ............................................................................79 Are they equal? ....................................................................................80 The old less-than, greater-than puzzle .............................................81 Even more comparisons! ....................................................................82 else, the Anti-if Statement ........................................................................83 Or Else! ...........................................................................................................83 Making Multiple Decisions ...........................................................................84 else if to the rescue! .......................................................................84 Get the order right! ..............................................................................85 Chapter 7: Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89 Presenting the for Loop ..............................................................................89 Dissecting the for loop ......................................................................90 Counting to 10 ......................................................................................91 Counting by twos .................................................................................93 Endless Loops ................................................................................................93 Your first endless loop ........................................................................94 A forever loop on purpose .................................................................95 Breaking out with break ....................................................................96 Nesting Loops ................................................................................................97 The 17,576 Names of God .............................................................................98 Multiple for Conditions ...............................................................................99 Chapter 8: Using Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Are Constants Necessary? .........................................................................101 A program example to drive home the point ................................101 But then, something changes! ..........................................................102 Chickening out and using variables instead ..................................103 Constants: The Anti-Variable! ....................................................................103 Declaring a constant .........................................................................104 Using constants in your code ..........................................................105 Other Things You Can #define ................................................................106 Chapter 9: Mysterious Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109 Math Review ................................................................................................109 The Sacred Order of Precedence ..............................................................110 My Dear Aunt Sally ............................................................................111 What about multiple multiplications? ............................................112 Fooling old Sally with parentheses .................................................113 Say It Out Loud: Unary Operators! ............................................................114 Going negative ...................................................................................114 Getting silly ........................................................................................115 Incrementing and Decrementing and Loving It .......................................115 Just add one to it ...............................................................................116 Just take one away from it ................................................................117 Pre-incrementing and post-incrementing .......................................117 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xi
C All-in-One Desk Reference For Dummiesxii Other Cryptic Math Shortcuts ...................................................................119 Incrementing by more than one ......................................................119 Multiplying a variable by itself ........................................................120 Chapter 10: It’s Only Logical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123 Comparisons from Hell ...............................................................................123 YORN.C, attempt number 1 ..............................................................123 YORN.C, attempt number 2 ..............................................................124 YORN.C, attempt number 3 ..............................................................125 Here Are Your Logical Operators, Mr. Spock! ..........................................127 Introducing Mr. Logical OR ...............................................................128 Say hello to Mr. Logical AND ............................................................129 YORN.C, attempt number 4 ..............................................................131 Multiple Madness with Logical Operators ...............................................132 Book II: Middle C ......................................................133 Chapter 1: Variables from Beyond Infinity . . . . . . . . . . . . . . . . . . . . . .135 Review of C Language Variable Types ......................................................135 The long and the short of it ...........................................................137 Not long enough ...............................................................................138 Float me to the moon ........................................................................139 Double or nothing! .............................................................................140 Signed, Unsigned, Soap, No Soap, Radio ..................................................141 Greetings, O Unsigned One ..............................................................142 Unsigned variables seem to lack that negative-attitude problem ............................................................144 One last twisty turn ...........................................................................145 Fair and Unfair Variables ............................................................................146 Typecasting and Other Acting Problems .................................................146 Pretending that a variable is something it’s not ............................146 Cast away! ...........................................................................................147 C Language Variable Reference .................................................................148 Chapter 2: The Madness of Printf() . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 Going Numb with Numbering Systems .....................................................149 Counting bases has nothing to do with baseball ..........................150 Base 2, or binary ................................................................................151 Base 16, or hexadecimal ...................................................................151 Displaying hex values with printf() ............................................153 Escape in hex .....................................................................................155 Base 8, or octal ..................................................................................156 It’s not a counting base — it’s scientific! ........................................157 Scientific notation is for floats only ................................................159 Using immediate scientific notation values ...................................160 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xii
Table of Contents xiii Putting Printf() to the Test ....................................................................160 Formatting floating-point numbers .................................................160 Setting the output width for values ................................................161 Padding integers ................................................................................162 A handy hex trick ..............................................................................163 Justifying text with printf() ..........................................................163 Other formatting options .................................................................164 Chapter 3: Maniacal Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . .165 The Symbols That C Forgot .......................................................................166 The root of the square ......................................................................166 Pow to the power of pow .................................................................167 Ah, the root of the cube! ...................................................................169 Logarithms .........................................................................................170 Trigonometric Functions ............................................................................171 The looming terror of radians and degrees ...................................171 Triangle hell .......................................................................................173 Other Handy Math Functions ....................................................................177 Working on your abs() ....................................................................177 Getting the abs() of a float ...........................................................179 Chapter 4: Not Truly Random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181 Introducing the random() Function .........................................................182 “Give me 100 really random numbers” ...........................................183 “Give me 100 really random numbers without much effort on my behalf this time” ......................................................184 The Diabolical Dr. Modulus ........................................................................185 Introducing the modulo operator ...................................................185 What does all this have to do with random numbers? .................186 Roll them bones! ................................................................................187 What number is rolled most often? .................................................188 Flip a coin 1,000 times .......................................................................190 Chapter 5: While Going Loopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193 The while Loop ..........................................................................................193 Constructing a basic while loop ....................................................194 Turn on the incredible shrinking ray! .............................................195 I could while away the hours .........................................................196 The popular while(!done) loop ....................................................197 The do-while Loop ....................................................................................199 Messing with Loops ....................................................................................201 The endless while loop ...................................................................201 Continuing loops ...............................................................................202 Nested while loops ..........................................................................203 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xiii
C All-in-One Desk Reference For Dummiesxiv Chapter 6: More Decision Making . . . . . . . . . . . . . . . . . . . . . . . . . . . .205 The Old Switch Case Trick ......................................................................205 The else-if else-if else-if else-if disease ............................................205 Introducing the cure: switch case ...............................................207 The switch case solution ..............................................................208 Aghgh! No breaks! ..............................................................................209 The switch case while(!done) trick ........................................211 The Weird and Creepy ?: Construct ........................................................212 Bonus Program! ...........................................................................................213 Chapter 7: The Goto Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217 What Now? Go To! .......................................................................................217 The Basic goto Thing .................................................................................217 Where goto Is Perhaps Needed ................................................................219 Book III: Above C Level .............................................221 Chapter 1: Asking for Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .223 Beyond Normal Variables ...........................................................................223 Making an array in C .........................................................................224 Using an array ....................................................................................225 Declaring an empty array .................................................................226 Refilling an array ................................................................................228 Sorting an Array ..........................................................................................229 Sort me, quickly! ................................................................................229 Sorting things out ..............................................................................230 Sorting an obscenely huge series of numbers ...............................234 Arrays from Beyond the First Dimension! ................................................235 Declaring a two-dimensional array .................................................236 Initializing a two-dimensional array ................................................236 Arrays in the twilight zone ...............................................................239 Bonus Program! ...........................................................................................240 Chapter 2: I Sing of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243 The Strings Review .....................................................................................243 Declaring strings ................................................................................243 Reading and writing strings .............................................................244 What you may think you can do, but cannot do, with strings .....................................................................................246 The Truth about Strings .............................................................................247 Deep inside the character array ......................................................247 Terminating a string (the NULL character) ....................................248 Messing with strings .........................................................................248 Lovely and Handy String Functions ..........................................................250 An overview of all the string functions ..........................................250 Copying a string .................................................................................251 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xiv
Table of Contents xv Comparing two strings .....................................................................253 Comparing two strings of unequal case .........................................254 Sticking two strings together ...........................................................254 How long is that string? ....................................................................256 The Boggling Concept of Arrays of Strings ..............................................257 3-dimensional string arrays .............................................................259 Fixing the dwarfs ...............................................................................261 Chapter 3: Messing with Characters . . . . . . . . . . . . . . . . . . . . . . . . . .265 Introducing the CTYPE Functions .............................................................265 Characters That Tell the Truth ..................................................................267 Just a Trivial Program Example .................................................................267 Altering Text ................................................................................................268 The droll “make me uppercase” program ......................................268 Yorn again? .........................................................................................269 Chapter 4: Stinkin’ Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .271 Life without Structures ...............................................................................271 Part I: The Oz database ....................................................................272 Part II: The Oz database grows ........................................................273 Part III: Arrays are not the answer ..................................................275 Multivariables! .............................................................................................277 Presenting the structure ...................................................................277 The lowdown on structures .............................................................278 More stuff ...........................................................................................280 Declaring and defining a structure ..................................................281 Arrays of Structures ....................................................................................283 Meanwhile, back in Oz . . . ................................................................284 Predefining an array of structures ..................................................285 Copying one structure element to another ....................................287 Structures for the Birds (Nested Structures) ..........................................289 Chapter 5: Creating Your Own Functions . . . . . . . . . . . . . . . . . . . . . . .293 Your Typical Function ................................................................................293 Making a function in C ......................................................................294 Using functions ..................................................................................295 The importance of prototyping .......................................................296 Functions That Don’t Func .........................................................................297 Using Variables in Functions ......................................................................298 The concept of local variables ........................................................298 Using global variables .......................................................................300 An example of a global variable in a real, live program ...............301 Functions That Eat Values ..........................................................................303 Here it comes! ....................................................................................304 How to send more than one value to a function ...........................306 Sending structures to functions ......................................................308 How to send strings (or arrays) to a function ...............................310 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xv
C All-in-One Desk Reference For Dummiesxvi Functions That Return a Value ..................................................................311 Returning a value with the return keyword .................................311 Roll ’dem bones! ................................................................................312 Functions That Do Both .............................................................................315 The Land of No Prototyping ......................................................................316 Chapter 6: Quitting Before You’re Done . . . . . . . . . . . . . . . . . . . . . . . .319 Abruptly Leaving the main() Function ....................................................319 Many happy returns ........................................................................319 Sending in your return early ..........................................................321 Finding the nearest exit() .............................................................322 Abort! Abort! Abort! ..........................................................................323 A Most Graceful Exit ...................................................................................324 If we ever get out of here. . . . ...........................................................325 Registering multiple functions .........................................................326 Chapter 7: More Variable Nonsense . . . . . . . . . . . . . . . . . . . . . . . . . . .329 The Joys of Hungarian Notation ................................................................329 Beware the typedef Statement! ...............................................................331 The silly way to use typedef ..........................................................331 Using typedef with structures .......................................................332 Where programmers get into trouble .............................................333 Other Funky Variable Things .....................................................................334 Auto .....................................................................................................335 Const ...................................................................................................335 Enum ...................................................................................................336 Register ...............................................................................................337 Static ...................................................................................................337 Volatile ................................................................................................341 The State of the union ...............................................................................342 A simple union ..................................................................................342 Unions buried inside structures ......................................................344 Book IV: Advanced C .................................................347 Chapter 1: Introduction to Evil Pointers . . . . . . . . . . . . . . . . . . . . . . . .349 Basic Boring Computer Memory Stuff ......................................................349 Truly random memory .....................................................................350 Buying the land, but not building the house .................................351 Some variables are greedier than others .......................................352 The lowdown on sizeof ..................................................................353 Calculating the size of an array .......................................................353 Location & location & location ........................................................355 It all boils down to this .....................................................................358 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xvi
Table of Contents xvii Some Pointers ..............................................................................................359 The simple definition of a pointer ...................................................359 A boring program that’s suitable as an example ...........................359 Making Mr. Pointer ............................................................................360 The converted metric-conversion program ...................................362 Snagging the address of an array ....................................................364 The Insanity of Pointer Arithmetic ...........................................................366 Elementary pointer math .................................................................367 More to the pointer ...........................................................................370 Chapter 2: Getting to the *Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373 Pointer Review .............................................................................................373 And Now, the Asterisk, Please ...................................................................374 Pointers that point and peek ...........................................................374 The pointer is a snoopy mailman ....................................................375 Using *pointers to Modify Variables .........................................................376 Changing a variable’s value with a pointer ....................................377 One pointer for everyone to share ..................................................378 Chapter 3: Binary Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .381 Say Hello to Mr. Bit ......................................................................................381 Counting by twos ...............................................................................382 Bits and bytes and words and long words .....................................385 Expressing binary values by using hexadecimal ...........................385 Basic Bit Twiddling .....................................................................................387 Doing the bit hula ..............................................................................388 The official >> format ........................................................................389 Shifting to the left ..............................................................................390 The Utter Inanity of Binary Logic ..............................................................391 Using the AND mask ..........................................................................391 One OR in the water ..........................................................................394 Displaying Binary Values ............................................................................395 The BinString() function ..............................................................395 Revisiting the logical OR ..................................................................397 Two Stragglers: ^ and ~ ..............................................................................398 The exclusive OR ...............................................................................399 The one’s complement .....................................................................400 Chapter 4: The Myth of the Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .403 Pointers and Arrays ....................................................................................403 Death to the Array! ......................................................................................404 Goodbye, array notation, Part I .......................................................404 Using a pointer to fill an array .........................................................405 And now, something to truly drive you nuts .................................406 “What if I want to increment the value and not the memory location?” ...................................................408 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xvii
C All-in-One Desk Reference For Dummiesxviii The Weird Relationship between Pointers and Array Brackets ............411 Goodbye, array notation, Part II ......................................................411 Removing all vestiges of array notation .........................................413 Proof for disbelievers ........................................................................414 More proof! .........................................................................................415 Arrays and Pointers Summary ..................................................................415 Chapter 5: Pointers and Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417 Using Pointers to Display Strings ..............................................................417 The boring way to display a string .................................................417 A better way to display a string ......................................................418 More tricks! ........................................................................................420 Even more tricks! ...............................................................................420 One last, crazy trick ..........................................................................421 Distinguishing Strings from Chars ............................................................422 The lowdown and letdown of library documentation ..................422 And, while I’m on the subject of weird strings ..............................425 Declaring a String by Using a Char Pointer ..............................................426 Chapter 6: Crazy Arrays of Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . .429 Introducing the Pointer Array ...................................................................429 Saving Some Space with String Pointer Arrays .......................................431 Wasting space with string arrays ....................................................431 Making a string pointer array ..........................................................432 A redundant demo program to prove that it works ......................434 Finding Characters in a Pointer String Array ..........................................436 More puzzles, more problems .........................................................436 Finding the pointer array without array notation .........................437 Pointers that point at pointers ........................................................439 Replacing the array[a][b] notation with pointers ....................441 Sorting Strings with Pointers .....................................................................443 A simple, though incorrect, string-sorting program .....................444 What went wrong ...............................................................................445 Digging for characters ......................................................................446 More sorting, more strings ...............................................................447 Chapter 7: Functions and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . .451 Passing a Pointer to a Function .................................................................451 Basic pointer-nonsense review ........................................................451 Know the differences between pointers and values .....................452 Functions that eat pointers ..............................................................453 The glorious advantage of passing a pointer .................................456 Returning a pointer from a function ...............................................457 Arrays to and from Functions ....................................................................460 Passing an array to a function .........................................................460 Down with array notation! ................................................................461 How big is that array? .......................................................................462 02_570692 ftoc.qxd 7/30/04 9:47 AM Page xviii
Comments 0
Loading comments...
Reply to Comment
Edit Comment