Learn C on the Mac DAVE MARK Learn C on the Mac Copyright © 2009 by Dave Mark All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-1809-8 ISBN-13 (electronic): 978-1-4302-1810-4 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Lead Editor: Clay Andres Technical Reviewer: Kevin O’Malley Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell, Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Project Manager: Beth Christmas Copy Editor: Heather Lang Associate Production Director: Kari Brooks-Copony Production Editor: Laura Esterman Compositor/Artist/Interior Designer: Diana Van Winkle Proofreader: Liz Welch Indexer: Toma Mulligan Cover Designer: Kurt Krames Manufacturing Director: Tom Debolski Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or visit http://www.springeronline.com. For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705. Phone 510-549-5930, fax 510-549-5939, e-mail [email protected], or visit http://www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at http://www.apress.com. To my incredible family, D3KR4FR Contents at a Glance About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xv About the Technical Reviewer .................................................xvii Acknowledgments ........................................................... xix Preface ....................................................................... xxi CHAPTER 1 Welcome Aboard ..............................................1 CHAPTER 2 Go Get the Tools! ...............................................5 CHAPTER 3 Programming Basics ..........................................17 CHAPTER 4 C Basics: Functions ............................................25 CHAPTER 5 C Basics: Variables and Operators ..............................49 CHAPTER 6 Controlling Your Program’s Flow ...............................85 CHAPTER 7 Pointers and Parameters .................................... 121 CHAPTER 8 Variable Data Types ......................................... 161 CHAPTER 9 Designing Your Own Data Structures ........................ 207 CHAPTER 10 Working with Files .......................................... 249 CHAPTER 11 Advanced Topics ............................................ 283 CHAPTER 12 Where Do You Go from Here? ................................ 317 APPENDIX Answers to Exercises ........................................ 323 INDEX ...................................................................... 336 v Contents About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xv About the Technical Reviewer .................................................xvii Acknowledgments ........................................................... xix Preface ....................................................................... xxi CHAPTER 1 Welcome Aboard................................1 Who Is This Book For? ..........................................1 The Lay of the Land ............................................2 CHAPTER 2 Go Get the Tools! ................................5 Create an ADC Account ........................................5 Download the Tools ............................................6 Installing the Tools .............................................8 Take Your Tools for aTest Drive ................................10 The Xcode Welcome Screen ..............................11 Creating Your First Xcode Project .........................11 Saving Your New Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13 Running the Project ......................................14 Your First Program .......................................14 Downloading the Book Projects ...............................16 Let’s Move On ................................................16 CHAPTER 3 Programming Basics........................... 17 Programming .................................................17 Some Alternatives to C ...................................18 What About Objective-C, C++, and Java?. . . . . . . . . . . . . . . . . .18 What’s the Best Language for Programming the Mac or iPhone? ....................................20 The Programming Process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20 Source Code .............................................21 Compiling Your Source Code .............................22 What’s Next? ..................................................24 vii viii CONTENTS CHAPTER 4 C Basics: Functions ............................ 25 C Functions ...................................................25 The Function Definition ..................................26 Syntax Errors and Algorithms .............................27 Calling aFunction .............................................29 A Brief History of C ............................................32 The Standard Library ..........................................33 Exploring Unix and Your Mac’s Built-In Manual .................34 Same Program, Two Functions .................................36 The hello2 Project ........................................37 The hello2 Source Code ..................................40 Running hello2 ..........................................42 Let’s Do That Again, Again, Again ..............................43 Generating Some Errors .......................................44 C Is Case Sensitive ............................................47 What’s Next? ..................................................47 CHAPTER 5 C Basics: Variables and Operators............... 49 An Introduction to Variables ...................................50 Working with Variables ...................................51 Variable Names ..........................................51 The Size of aType ........................................52 Bytes and Bits ............................................53 Going from 1 Byte to 2 Bytes .............................55 Operators ....................................................56 The +, -, ++, and -- Operators .............................57 The += and -= Operators .................................58 The *,/,*=,and /= Operators .............................59 Using Parentheses ............................................60 Operator Precedence .........................................61 Sample Programs .............................................63 Opening operator.xcodeproj .............................63 Stepping Through the operator Source Code ..............64 Opening postfix.xcode ...................................67 Stepping Through the postfix Source Code ...............68 Backslash Combinations ..................................70 Support for Backslash Combinations ......................71 Running slasher ..........................................72 Stepping Through the slasher Source Code ...............73 CONTENTS ix Building slasher the Unix Way ............................74 Which Compiler Did You Run? ............................76 Running the Unix Version of slasher .......................77 Sprucing Up Your Code .......................................77 Source Code Spacing .....................................78 Comment Your Code .....................................80 The Curly Brace Controversy ..............................81 What’s Next? ..................................................82 CHAPTER 6 Controlling Your Program’s Flow................ 85 Flow Control ..................................................85 The if Statement .........................................86 Expressions ...................................................88 True Expressions .........................................88 Comparative Operators ..................................89 Logical Operators ........................................90 truthTester.xcodeproj ....................................94 Compound Expressions ..................................94 Statements ..............................................95 The Curly Braces .........................................96 Where to Place the Semicolon ............................98 The Loneliest Statement ..................................98 The while Statement .....................................98 The for Statement ...................................... 101 loopTester.xcodeproj ................................... 104 The do Statement ...................................... 107 The switch Statement .................................. 107 Breaks in Other Loops .................................. 111 isOdd.xcodeproj ....................................... 111 Stepping Through the isOdd Source Code .............. 112 nextPrime.xcodeproj ................................... 114 Stepping Through the nextPrime Source Code .......... 115 What’s Next? ................................................ 118 CHAPTER 7 Pointers and Parameters...................... 121 What Is aPointer? ........................................... 121 Why Use Pointers? ..................................... 122 Checking Out of the Library ............................ 124 x CONTENTS Pointer Basics ............................................... 124 Variable Addresses ..................................... 125 The & Operator ........................................ 126 Declaring aPointer Variable ............................ 126 Function Parameters ........................................ 131 What Are Function Parameters? ........................ 132 Variable Scope ......................................... 132 How Function Parameters Work ........................ 133 Parameters Are Temporary ............................. 135 The Difference Between Arguments and Parameters .... 136 What Does All This Have to Do with Pointers? ................ 137 Global Variables and Function Returns ....................... 140 Global Variables ........................................ 140 Adding Globals to Your Programs ....................... 141 Function Returns ....................................... 142 printf() Returns aValue ................................. 145 Danger! Avoid Uninitialized Return Values! .............. 145 To Return or Not to Return?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 More Sample Programs ..................................... 146 listPrimes.xcode ........................................ 147 power.xcodeproj ....................................... 149 Using the Debugger ........................................ 153 What’s Next? ................................................ 157 CHAPTER 8 Variable Data Types .......................... 161 Data Types Beyond int ...................................... 161 floatSizer .............................................. 162 Walking Through the floatSizer Source Code ............ 163 The Integer Types ...................................... 168 Type Value Ranges ..................................... 169 Memory Efficiency vs. Safety. . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Working with Characters .................................... 172 The ASCII Character Set ................................ 172 ascii.xcodeproj ......................................... 173 Stepping Through the acsii Source Code ................ 177 Arrays ...................................................... 178 Why Use Arrays? ....................................... 179 dice.xcode ............................................. 180 Stepping Through the dice Source Code ................ 181 Danger, Will Robinson! ...................................... 184 CONTENTS xi Text Strings ................................................. 185 A Text String in Memory ................................ 185 nameBad.xcodeproj .................................... 186 Stepping Through the nameBad Source Code ........... 187 The Input Buffer ........................................ 188 On with the Program ................................... 190 The Problem with nameBad ............................ 191 The nameGood Source Code ........................... 193 The #define Directive ....................................... 194 Function-Like #define Macros .......................... 196 wordCount.xcodeproj .................................. 198 Stepping Through the wordCount Source Code ......... 199 What’s Next? ................................................ 203 CHAPTER 9 Designing Your Own Data Structures .......... 207 Bundling Your Data ......................................... 207 Model A: Three Arrays ....................................... 208 multiArray.xcodeproj ................................... 210 Stepping Through the multiArray Source Code .......... 211 Getting Rid of the Extra Carriage Return ................ 217 Adding Error Handling ................................. 217 Walking Through the multiArrayWithErrCode Source Code ........................................ 218 Finishing Up With Model A .................................. 220 Model B: The Data Structure Approach ...................... 222 structSize.xcode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Stepping Through the structSize Source Code ........... 223 Passing astruct As aParameter .............................. 226 Passing aCopy of the struct ............................ 228 paramAddress.xcodeproj ............................... 229 struct Arrays ........................................... 230 Allocating Your Own Memory ............................... 231 Using malloc() ......................................... 232 free() .................................................. 234 Keeping Track of That Address! ......................... 234 Working with Linked Lists ................................... 235 Why Use Linked Lists? .................................. 236 Creating aLinked List .................................. 236 dvdTracker.xcodeproj .................................. 237 Stepping Through the dvdTracker Source Code ......... 239 What’s Next? ................................................ 247