Tải bản đầy đủ (.pdf) (548 trang)

IT training teach yourself c in 24 hours (2nd ed ) zhang 2000 02 28

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.22 MB, 548 trang )


Teach Yourself

C
in
Tony Zhang

24
Hours
SECOND EDITION

201 West 103rd St., Indianapolis, Indiana, 46290 USA


Sams Teach Yourself C in 24 Hours,
Second Edition
Copyright ©2000 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of
the information contained herein.
International Standard Book Number: 0-672-31861-x
Library of Congress Catalog Card Number: 99-067311
Printed in the United States of America
First Printing: February, 2000
05

04


03

6

5

ASSOCIATE PUBLISHER
Michael Stephens

ACQUISITIONS EDITOR
Carol Ackerman

DEVELOPMENT EDITOR
Gus A. Miklos

MANAGING EDITOR
Charlotte Clapp

PROJECT EDITOR
Andy Beaster

COPY EDITOR
Kate Givens

INDEXERS
Christine Nelsen
Deborah Hittel

PROOFREADER
4


3

Trademarks
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to the
accuracy of this information. Use of a term in this book should not be regarded
as affecting the validity of any trademark or service mark.

Candice Hightower

TECHNICAL EDITOR
Bill Mitchell

TEAM COORDINATOR
Pamalee Nelson

INTERIOR DESIGNER
Gary Adair

Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as
possible, but no warranty or fitness is implied. The information provided is on
an “as is” basis. The author and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

COVER DESIGNER
Aren Howell

COPYWRITER

Eric Borgert

EDITORIAL ASSISTANT
Angela Boley

PRODUCTION
Stacey DeRome
Mark Walchle


Contents at a Glance
Introduction

Part I The Basics of C
Hour 1

1

9

Taking the First Step

11

2

Writing Your First C Program

27


3

Learning the Structure of a C Program

41

4

Understanding Data Types and Keywords

55

5

Handling Standard Input and Output

71

Part II Operators and Control-flow Statements
Hour 6

Manipulating Data

89
91

7

Working with Loops


105

8

Using Conditional Operators

121

9

Working with Data Modifiers and Math Functions

141

Controlling Program Flow

155

10

Part III Pointers and Arrays
Hour 11

173

Understanding Pointers

175

12


Understanding Arrays

189

13

Manipulating Strings

207

14

Understanding Scope and Storage Classes

223

Part IV Functions and Dynamic Memory Allocation
Hour 15

241

Working with Functions

243

16

Applying Pointers


259

17

Allocating Memory

279

18

Using Special Data Types and Functions

295


Part V Structure, Union, File I/O, and More
Hour 19

311

Understanding Structures

313

20

Understanding Unions

333


21

Reading and Writing with Files

355

22

Using Special File Functions

373

23

Compiling Programs: The C Preprocessor

391

24

Where Do You Go from Here?

409

Part VI Appendixes
Appendix A
B

437


ANSI Standard Header Files

439

Answers to Quiz Questions and Exercises

441

Index

503


Table of Contents
Introduction

1

Who Should Read This Book? ................................................................................1
Special Features of This Book ................................................................................1
Programming Examples ..........................................................................................2
Q&A and Workshop ................................................................................................4
Conventions Used in This Book ..............................................................................4
What You’ll Learn in 24 Hours................................................................................4

Part I The Basics of C
Hour 1 Taking the First Step

9
11


What Is C? ............................................................................................................12
The ANSI C Standard ..........................................................................................15
Assumptions About You ........................................................................................16
Setting Up Your System ........................................................................................16
Hardware ..........................................................................................................16
Software............................................................................................................16
A Sample C Programming Setup ....................................................................17
Using Microsoft’s Compiler ............................................................................18
Using Borland’s Compiler................................................................................21
Summary ................................................................................................................24
Q&A ......................................................................................................................25
Workshop ..............................................................................................................25
Quiz ..................................................................................................................25
Hour 2 Writing Your First C Program

27

A Simple C Program..............................................................................................28
Comments ..............................................................................................................29
The #include Directive ........................................................................................31
Header Files......................................................................................................32
Angle Brackets (< >) and Double Quotes (“ “) ..............................................32
The main() Function..............................................................................................33
The Newline Character (\n) ............................................................................33
The return Statement ......................................................................................34
The exit() Function ........................................................................................34
Compiling and Linking..........................................................................................34
What’s Wrong with My Program? ........................................................................36
Debugging Your Program ......................................................................................37



vi

Sams Teach Yourself C in 24 Hours

Summary ................................................................................................................37
Q&A ......................................................................................................................38
Workshop ..............................................................................................................38
Quiz ..................................................................................................................38
Exercises ..........................................................................................................39
Hour 3 Learning the Structure of a C Program

41

The Basics of a C Program....................................................................................42
Constants and Variables....................................................................................42
Expressions ......................................................................................................42
Statements ........................................................................................................45
Statement Blocks ..............................................................................................45
Anatomy of a C Function ......................................................................................46
Determining a Function’s Type ........................................................................46
Giving a Function a Valid Name ......................................................................47
Passing Arguments to C Functions ..................................................................47
The Beginning and End of a Function ............................................................48
The Function Body ..........................................................................................48
Making Function Calls ..........................................................................................49
Summary ................................................................................................................51
Q&A ......................................................................................................................52
Workshop ..............................................................................................................52

Quiz ..................................................................................................................52
Exercises ..........................................................................................................53
Hour 4 Understanding Data Types and Keywords

55

C Keywords ..........................................................................................................56
The char Data Type ..............................................................................................57
Character Variables ..........................................................................................58
Character Constants..........................................................................................58
The Escape Character (\) ..................................................................................59
Printing Characters ..........................................................................................60
The int Data Type ................................................................................................62
Declaring Integer Variables ..............................................................................62
Showing the Numeric Values of Characters ....................................................63
The float Data Type ............................................................................................64
Declaring Floating-Point Variables ..................................................................64
The Floating-Point Format Specifier (%f) ........................................................65
The double Data Type ..........................................................................................67
Using Scientific Notation ......................................................................................67
Naming a Variable..................................................................................................68
Summary ................................................................................................................68
Q&A ......................................................................................................................68


Contents

vii

Workshop ..............................................................................................................69

Quiz ..................................................................................................................69
Exercises ..........................................................................................................70
Hour 5 Handling Standard Input and Output

71

Understanding Standard I/O ................................................................................72
Getting Input from the User ..................................................................................72
Using the getc() Function ..............................................................................72
Using the getchar() Function ........................................................................74
Printing Output on the Screen ..............................................................................75
Using the putc() Function ..............................................................................75
Another Function for Writing: putchar() ......................................................77
Revisiting the printf() Function..........................................................................78
Converting to Hex Numbers ............................................................................79
Specifying the Minimum Field Width..............................................................81
Aligning Output................................................................................................83
Using the Precision Specifier ..........................................................................84
Summary ................................................................................................................85
Q&A ......................................................................................................................86
Workshop ..............................................................................................................86
Quiz ..................................................................................................................87
Exercises ..........................................................................................................87

Part II Operators and Control-flow Statements
Hour 6 Manipulating Data

89
91


Arithmetic Assignment Operators ........................................................................92
The Assignment Operator (=) ..........................................................................92
Combining Arithmetic Operators with = ..........................................................92
Getting Negations of Numeric Values ..................................................................95
Incrementing or Decrementing by One ................................................................96
Greater Than or Less Than? ..................................................................................98
Using the Cast Operator ......................................................................................101
Summary ..............................................................................................................102
Q&A ....................................................................................................................102
Workshop ............................................................................................................103
Quiz ................................................................................................................103
Exercises ........................................................................................................103
Hour 7 Working with Loops

105

The while Loop ..................................................................................................106
The do-while Loop..............................................................................................107
Looping Under the for Statement ......................................................................109


viii

Sams Teach Yourself C in 24 Hours

The Null Statement ..............................................................................................112
Using Complex Expressions in a for Statement............................................113
Using Nested Loops ............................................................................................116
Summary ..............................................................................................................118
Q&A ....................................................................................................................118

Workshop ............................................................................................................119
Quiz ................................................................................................................119
Exercises ........................................................................................................120
Hour 8 Using Conditional Operators

121

Measuring Data Sizes ..........................................................................................122
Everything Is Logical ..........................................................................................124
The Logical AND Operator (&&) ....................................................................124
The Logical OR Operator (||) ......................................................................126
The Logical NEGATION Operator (!) ..........................................................128
Manipulating Bits ................................................................................................129
Converting Decimal to Hex or Binary ..........................................................129
Using Bitwise Operators ................................................................................130
Using Shift Operators ....................................................................................133
What Does x?y:z Mean? ....................................................................................135
Summary ..............................................................................................................137
Q&A ....................................................................................................................137
Workshop ............................................................................................................138
Quiz ................................................................................................................138
Exercises ........................................................................................................138
Hour 9 Working with Data Modifiers and Math Functions

141

Enabling or Disabling the Sign Bit......................................................................142
The signed Modifier ......................................................................................142
The unsigned Modifier ..................................................................................143
Changing Data Sizes............................................................................................145

The short Modifier ........................................................................................145
The long Modifier ..........................................................................................145
Adding h, l, or L to printf and fprintf Format Specifiers..........................147
Mathematical Functions in C ..............................................................................148
Calling sin(), cos(), and tan() ....................................................................149
Calling pow() and sqrt() ..............................................................................150
Summary ..............................................................................................................152
Q&A ....................................................................................................................153
Workshop ............................................................................................................154
Quiz ................................................................................................................154
Exercises ........................................................................................................154


Contents

Hour 10 Controlling Program Flow

ix

155

Always Saying “if…” ..........................................................................................156
The if-else Statement ..................................................................................158
Nested if Statements......................................................................................160
The switch Statement..........................................................................................161
The break Statement............................................................................................164
Breaking an Infinite Loop....................................................................................166
The continue Statement ......................................................................................167
The goto Statement..............................................................................................168
Summary ..............................................................................................................170

Q&A ....................................................................................................................170
Workshop ............................................................................................................171
Quiz ................................................................................................................171
Exercises ........................................................................................................172

Part III Pointers and Arrays
Hour 11 Understanding Pointers

173
175

What Is a Pointer?................................................................................................176
Address (Left Value) Versus Content (Right Value) ............................................176
The Address-of Operator (&) ..........................................................................177
Declaring Pointers................................................................................................179
The Dereference Operator (*) ........................................................................182
Null Pointers ..................................................................................................183
Updating Variables via Pointers ..........................................................................183
Pointing to the Same Memory Location..............................................................184
Summary ..............................................................................................................186
Q&A ....................................................................................................................187
Workshop ............................................................................................................188
Quiz ................................................................................................................188
Exercises ........................................................................................................188
Hour 12 Understanding Arrays

189

What Is an Array? ................................................................................................190
Declaring Arrays ............................................................................................190

Indexing Arrays ..............................................................................................190
Initializing Arrays ..........................................................................................191
The Size of an Array............................................................................................192
Arrays and Pointers..............................................................................................194
Displaying Arrays of Characters ....................................................................196
The Null Character (‘\0’)..............................................................................198
Multidimensional Arrays ....................................................................................199


x

Sams Teach Yourself C in 24 Hours

Unsized Arrays ....................................................................................................201
Summary ..............................................................................................................203
Q&A ....................................................................................................................203
Workshop ............................................................................................................204
Quiz ................................................................................................................204
Exercises ........................................................................................................205
Hour 13 Manipulating Strings

207

Declaring Strings ................................................................................................208
What Is a String? ............................................................................................208
Initializing Strings ..........................................................................................208
String Constants versus Character Constants ................................................209
How Long Is a String? ........................................................................................212
The strlen() Function ..................................................................................212
Copying Strings with strcpy() ......................................................................213

Reading and Writing Strings ..............................................................................215
The gets() and puts() Functions..................................................................215
Using %s with the printf() Function ............................................................217
The scanf() Function ....................................................................................217
Summary ..............................................................................................................219
Q&A ....................................................................................................................220
Workshop ............................................................................................................221
Quiz ................................................................................................................221
Exercises ........................................................................................................221
Hour 14 Understanding Scope and Storage Classes

223

Hiding Data..........................................................................................................224
Block Scope....................................................................................................224
Nested Block Scope........................................................................................225
Function Scope ..............................................................................................226
Program Scope................................................................................................227
The Storage Class Specifiers ..............................................................................229
The auto Specifier ..........................................................................................229
The static Specifier ......................................................................................230
File Scope and the Hierarchy of Scopes ........................................................232
The register Specifier ..................................................................................233
The extern Specifier ......................................................................................233
The Storage Class Modifiers ..............................................................................234
The const Modifier ........................................................................................234
The volatile Modifier ..................................................................................235
Summary ..............................................................................................................236
Q&A ....................................................................................................................237



Contents

xi

Workshop ............................................................................................................238
Quiz ................................................................................................................238
Exercises ........................................................................................................239

Part IV Functions and Dynamic Memory Allocation
Hour 15 Working with Functions

241
243

Declaring Functions ............................................................................................244
Declaration Versus Definition ........................................................................244
Specifying Return Types ................................................................................244
Using Prototypes ............................................................................................245
Making Function Calls ..................................................................................245
Prototyping Functions..........................................................................................247
Functions with No Arguments........................................................................248
Using time(), localtime(), and asctime() ..................................................249
Functions with a Fixed Number of Arguments ..............................................251
Prototyping a Variable Number of Arguments ..............................................251
Processing Variable Arguments ......................................................................252
Learning Structured Programming ......................................................................255
Summary ..............................................................................................................255
Q&A ....................................................................................................................256
Workshop ............................................................................................................257

Quiz ................................................................................................................257
Exercises ........................................................................................................257
Hour 16 Applying Pointers

259

Pointer Arithmetic................................................................................................259
The Scalar Size of Pointers ............................................................................260
Pointer Subtraction ........................................................................................263
Pointers and Arrays..............................................................................................264
Accessing Arrays via Pointers........................................................................264
Pointers and Functions ........................................................................................266
Passing Arrays to Functions ..........................................................................266
Passing Pointers to Functions ........................................................................268
Passing Multidimensional Arrays as Arguments............................................270
Arrays of Pointers ................................................................................................272
Pointing to Functions ..........................................................................................274
Summary ..............................................................................................................276
Q&A ....................................................................................................................276
Workshop ............................................................................................................277
Quiz ................................................................................................................277
Exercises ........................................................................................................278


xii

Sams Teach Yourself C in 24 Hours

Hour 17 Allocating Memory


279

Allocating Memory at Runtime ..........................................................................280
The malloc() Function........................................................................................280
Releasing Allocated Memory with free() ..........................................................283
The calloc() Function........................................................................................286
The realloc() Function ......................................................................................288
Summary ..............................................................................................................291
Q&A ....................................................................................................................292
Workshop ............................................................................................................293
Quiz ................................................................................................................293
Exercises ........................................................................................................294
Hour 18 Using Special Data Types and Functions

295

The enum Data Type ............................................................................................296
Declaring the enum Data Type ........................................................................296
Assigning Values to enum Names ..................................................................296
Making typedef Definitions................................................................................300
Why Use typedef? ..............................................................................................300
Recursive Functions ............................................................................................303
Revisiting the main() Function............................................................................305
Command-Line Arguments ............................................................................305
Receiving Command-Line Arguments ..........................................................306
Summary ..............................................................................................................308
Q&A ....................................................................................................................308
Workshop ............................................................................................................309
Quiz ................................................................................................................309
Exercises ........................................................................................................310


Part V Structure, Union, File I/O, and More
Hour 19 Understanding Structures

311
313

What Is a Structure? ............................................................................................314
Declaring Structures ......................................................................................314
Defining Structure Variables ..........................................................................315
Referencing Structure Members with the Dot Operator ....................................315
Initializing Structures ..........................................................................................317
Structures and Function Calls..............................................................................319
Referencing Structures with Pointers ............................................................322
Referencing a Structure Member with -> ......................................................324
Arrays of Structures ............................................................................................324
Nested Structures............................................................................................327
Summary ..............................................................................................................330


Contents

xiii

Q&A ....................................................................................................................330
Workshop ............................................................................................................331
Quiz ................................................................................................................331
Exercises ........................................................................................................332
Hour 20 Understanding Unions


333

What Is a Union? ................................................................................................334
Declaring Unions............................................................................................334
Defining Union Variables ..............................................................................334
Referencing a Union with . or -> ..................................................................335
Unions versus Structures ....................................................................................337
Initializing a Union ........................................................................................337
The Size of a Union........................................................................................339
Using Unions ......................................................................................................341
Referencing the Same Memory Location Differently....................................341
Making Structures Flexible ............................................................................343
Defining Bit Fields with struct ....................................................................347
Summary ..............................................................................................................350
Q&A ....................................................................................................................351
Workshop ............................................................................................................352
Quiz ................................................................................................................352
Exercises ........................................................................................................353
Hour 21 Reading and Writing with Files

355

Files Versus Streams ............................................................................................356
What Is a File?................................................................................................356
What Is a Stream? ..........................................................................................356
Buffered I/O....................................................................................................356
The Basics of Disk File I/O ................................................................................357
Pointers of FILE ............................................................................................357
Opening a File ................................................................................................357
Closing a File..................................................................................................358

Reading and Writing Disk Files ..........................................................................360
One Character at a Time ................................................................................360
One Line at a Time ........................................................................................363
One Block at a Time ......................................................................................366
Summary ..............................................................................................................370
Q&A ....................................................................................................................370
Workshop ............................................................................................................371
Quiz ................................................................................................................371
Exercises ........................................................................................................372


xiv

Sams Teach Yourself C in 24 Hours

Hour 22 Using Special File Functions

373

Random Access to Disk Files ..............................................................................374
The fseek() and ftell() Functions..............................................................374
The rewind() Function ..................................................................................378
More Examples of Disk File I/O ........................................................................378
Reading and Writing Binary Data ..................................................................378
The fscanf() and fprintf() Functions ........................................................381
Redirecting the Standard Streams with freopen() ........................................384
Summary ..............................................................................................................387
Q&A ....................................................................................................................387
Workshop ............................................................................................................388
Quiz ................................................................................................................388

Exercises ........................................................................................................389
Hour 23 Compiling Programs: The C Preprocessor

391

What Is the C Preprocessor?................................................................................392
The C Preprocessor versus the Compiler ............................................................392
The #define and #undef Directives ....................................................................393
Defining Function-Like Macros with #define ..............................................394
Nested Macro Definitions ..............................................................................396
Compiling Your Code Under Conditions ............................................................397
The #ifdef and #endif Directives ................................................................397
The #ifndef Directive ....................................................................................397
The #if, #elif, and #else Directives ............................................................399
Nested Conditional Compilation ....................................................................402
Summary ..............................................................................................................405
Q&A ....................................................................................................................405
Workshop ............................................................................................................406
Quiz ................................................................................................................406
Exercises ........................................................................................................407
Hour 24 Where Do You Go from Here?

409

Creating a Linked List ........................................................................................410
Programming Style ..............................................................................................418
Modular Programming ........................................................................................419
Debugging............................................................................................................420
What You Have Learned ......................................................................................420
C Keywords ....................................................................................................420

Operators ........................................................................................................421
Constants ........................................................................................................422
Data Types ......................................................................................................423
Expressions and Statements ..........................................................................426
Control Flow Statements ................................................................................426


Contents

xv

Pointers ..........................................................................................................430
Functions ........................................................................................................432
Input and Output (I/O)....................................................................................433
The C Preprocessor ........................................................................................434
The Road Ahead… ..............................................................................................434
Summary ..............................................................................................................435

Part VI Appendixes

437

Appendix A ANSI Standard Header Files

439

Appendix B Answers to Quiz Questions and Exercises

441


Hour 1, “Taking the First Step” ..........................................................................441
Quiz ................................................................................................................441
Hour 2, “Writing Your First C Program” ............................................................442
Quiz ................................................................................................................442
Exercises ........................................................................................................442
Hour 3, “Learning the Structure of a C Program” ..............................................443
Quiz ................................................................................................................443
Exercises ........................................................................................................444
Hour 4, “Understanding Data Types and Keywords”..........................................445
Quiz ................................................................................................................445
Exercises ........................................................................................................445
Hour 5, “Handling Standard Input and Output”..................................................447
Quiz ................................................................................................................447
Exercises ........................................................................................................447
Hour 6, “Manipulating Data” ..............................................................................449
Quiz ................................................................................................................449
Exercises ........................................................................................................449
Hour 7, “Working with Loops” ..........................................................................451
Quiz ................................................................................................................451
Exercises ........................................................................................................451
Hour 8, “Using Conditional Operators” ..............................................................453
Quiz ................................................................................................................453
Exercises ........................................................................................................453
Hour 9, “Working with Data Modifiers and Math Functions”............................455
Quiz ................................................................................................................455
Exercises ........................................................................................................456
Hour 10, “Controlling Program Flow” ................................................................458
Quiz ................................................................................................................458
Exercises ........................................................................................................458



xvi

Sams Teach Yourself C in 24 Hours

Hour 11, “Understanding Pointers” ....................................................................460
Quiz ................................................................................................................460
Exercises ........................................................................................................461
Hour 12, “Understanding Arrays” ......................................................................462
Quiz ................................................................................................................462
Exercises ........................................................................................................463
Hour 13, “Manipulating Strings” ........................................................................465
Quiz ................................................................................................................465
Exercises ........................................................................................................466
Hour 14, “Understanding Scope and Storage Classes” ......................................467
Quiz ................................................................................................................467
Exercises ........................................................................................................468
Hour 15, “Working with Functions”....................................................................470
Quiz ................................................................................................................470
Exercises ........................................................................................................470
Hour 16, “Applying Pointers”..............................................................................473
Quiz ................................................................................................................473
Exercises ........................................................................................................474
Hour 17, “Allocating Memory” ..........................................................................476
Quiz ................................................................................................................476
Exercises ........................................................................................................476
Hour 18, “Using Special Data Types and Functions” ........................................480
Quiz ................................................................................................................480
Exercises ........................................................................................................480
Hour 19, “Understanding Structures”..................................................................482

Quiz ................................................................................................................482
Exercises ........................................................................................................482
Hour 20, “Understanding Unions” ......................................................................486
Quiz ................................................................................................................486
Exercises ........................................................................................................486
Hour 21, “Reading and Writing with Files”........................................................490
Quiz ................................................................................................................490
Exercises ........................................................................................................490
Hour 22, “Using Special File Functions” ............................................................494
Quiz ................................................................................................................494
Exercises ........................................................................................................494
Hour 23, “Compiling Programs: The C Preprocessor” ......................................499
Quiz ................................................................................................................499
Exercises ........................................................................................................500
Index

503


About the Author
TONY ZHANG has more than 15 years experience in computer programming and enterprise-wide information system design. He is currently working for one of the “big 5”
consulting firms focusing on e-business related infrastructure design, development, and
implementation.
With a Masters degree in Physics, he has published dozens of research papers on lasers
and computer programming. Among his broad interests are oil painting and photography,
the two things that Tony enjoys most.
You can reach Tony through Sams Publishing, or by emailing him at


About the Contributing Author

JOHN SOUTHMAYD is a Software Design Engineer with experience in areas ranging from
systems-level programming and device drivers to Windows development and Internet
technologies. He currently works as a consultant with Excell Data Corporation and lives
with his wife in Kirkland, Washington.


Dedication
To my wife, Ellen, and my parents, Zhi-ying and Bing-rong, for their love and inspirations.
—Tony Zhang

Acknowledgments
First, I’d like to thank the readers of the first edition of the book for their encouragement,
patience, comments, and especially, criticisms, which made the second edition more suitable for people who want to start a journey in the C programming world.
It’s my great pleasure to work with editor Sharon Cox for the second time. I’d like to
thank editors Carol Ackerman and Gus Miklos, and contributing author John Southmayd
for their excellent work that made the second edition of the book more accessible, and
largely, if not completely, error-free. Also, I’d like to express my appreciation to the great
work of the other editing team members. Together, they made the second edition possible.
I greatly appreciate the love and support of my wife, Ellen, who inspires me to look at
the technology world from different perspectives. It’s always a great joy to discuss issues
on philosophy and literature with her. My parents, whom I can never thank enough, gave
me not only love and affection, but also the opportunity of receiving the best education I
could ever have when I was in China.


Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value
your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.

As an Associate Publisher for Sams, I welcome your comments. You can fax, email, or
write me directly to let me know what you did or didn’t like about this book—as well as
what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this
book, and that due to the high volume of mail I receive, I might not be able to reply to
every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or fax number. I will carefully review your comments and share them
with the author and editors who worked on the book.
Fax:
317-581-4770
Email:
Mail: Michael Stephens
Associate Publisher
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA



Introduction
If one learns from others but does not think, one will be bewildered;
If one thinks but does not learn from others, one will be in peril.
—Confucius
Welcome to the second edition of Teach Yourself C in 24 Hours!
Based on the success of the first edition of the book and the feedback from the readers,
we have re-written or modified every single chapter of the book to make the second edition more suitable for beginners like you who want to get started with the C programming language as quickly as possible.
Of course, it’s very normal to spend more than 24 hours to really understand the concepts and programming skills introduced in the book. However, the good news is that
this book offers many sample programs and exercises with clear explanations and
answers, which makes the concepts of the C language easier to understand.

In fact, Teach Yourself C in 24 Hours provides a good starting point for you in C programming. It covers important topics in C programming, and lays a solid foundation for
a serious beginner like you. After reading this book, you’ll be able to write basic C programs on your own.
You will profit from reading the book when you start to apply C programs to real problems or move on to learn other programming languages, such as Perl, C++, and Java.

Who Should Read This Book?
If this is your first time learning C, this book is written for you. In fact, in writing this
book I assume that the readers have no previous programming experience. Of course, it’s
always a big plus if you have some knowledge of computers.

Special Features of This Book
This book contains the following special elements that make it simpler and clearer for
you to digest the rudimentary features and concepts of C as they are introduced:
• Syntax boxes
• Notes
• Cautions
• Tips


2

Sams Teach Yourself C in 24 Hours

, SYNTAX

Syntax boxes explain some of the more complicated features of C, such as control structures. Each syntax box consists of a formal definition of the feature followed by an
explanation. Here is an example of a syntax box:
The syntax for the malloc() function is
#include <stdlib.h>
void *malloc(size_t size);


,

Here, size specifies the number of bytes of storage to allocate. The header file,
stdlib.h, has to be included before the malloc() function can be called. Because the
malloc() function returns a void pointer, its type is automatically converted to the type
of pointer on the left side of an assignment operator.
(You’ll learn more about the malloc() function later in the book.)
Notes are explanations of interesting properties of a particular C program feature. Let’s
have a look at the following example of a note:

In left-justified output, the value being displayed appears at the left end of
the value field. In right-justified output, the value being displayed appears
at the right end of the value field.

Warnings warn you of programming pitfalls you should avoid. Here is a typical warning:

Never use the reserved keywords in C, nor names of the C library functions
as variable names in your program.

Tips are hints on how to write your C programs better. The following is an example of
a tip:

If you have a complex programming project, break it into smaller pieces.
And try to make one function do one thing and do it very well.

Programming Examples
As mentioned earlier, this book contains many useful programming examples with explanations. These examples are meant to show you how to use different data types and functions provided in C.


Introduction


Each example has a listing of the C program; the output generated from that listing will
follow. The example also offers an analysis of how the program works. Special icons are
used to point out each part of the example: Type, Input/Output, and Analysis.
In the example shown in Listing IN.1, there are some special typographic conventions.
The input you enter is shown in bold monospace type, and the output generated by the
executable program of Listing IN.1 is shown in plain monospace type.

TYPE
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

LISTING IN.1

Read in a Character Entered by the User

/* INL01.c: Read input by calling getc() */
#include <stdio.h>
main()
{

int ch;
printf(“Please type in one character:\n”);
ch = getc(stdin);
printf(“The character you just entered is: %c\n”, ch);
return 0;
}

The following output is displayed after the executable file, INL01.exe, is created and
executed. The user enters the H character, and the program displays what the user
entered.
Please type in one character:
H
The character you just entered is: H

In line 2 of Listing IN.1, the header file stdio.h is included for both the getc()
and printf() functions used in the program. Lines 4–12 give the name and body
of the main() function.

ANALYSIS

In line 6, an integer variable ch is declared, which is assigned to the return value from
the getc() function later in line 9. Line 8 prints out a piece of message that asks the user
to enter one character from the keyboard. The printf() function in line 8 uses the
default standard output stdout to display messages on the screen.
In line 9, the standard input stdin is passed to the getc() function, which indicates that
the file stream is from the keyboard. After the user types in a character, the getc() function returns the numeric value (that is, an integer) of the character. Note that in line 9 the
numeric value is assigned to the integer variable ch.

3



4

Sams Teach Yourself C in 24 Hours

In line 10, the character entered is displayed on the screen with the help of printf().
Note that the character format specifier %c is used within the printf() function in line 10.

Q&A and Workshop
Each hour (that is, each chapter) ends with a Q&A section that contains answers to common questions relating to the lesson of the chapter. Following the Q&A section there is a
Workshop that consists of quiz questions and programming exercises. The answers to
these quiz questions and sample solutions for the exercises are presented in Appendix D,
“Answers to Quiz and Exercises.”
To help you solidify your understanding of each lesson, you are encouraged to try to
answer the quiz questions and finish the exercises provided in the workshop.

Conventions Used in This Book
This book uses special typefaces to help you differentiate between C code and regular
English, and to identify important concepts.
• Actual C code is typeset in a special monospace font. You’ll see this font used in
listings, Input/Ouput examples, and code snippets. In the explanation of C features,
commands, filenames, statements, variables, and any text you see on the screen are
also typeset in this font.
• Command input and anything that you are supposed to enter appears in a bold
monospace font. You’ll see this mainly in the Input/Output sections of examples.
• Placeholders in syntax descriptions appear in an italic monospace font. Replace
the placeholder with the actual filename, parameter, or whatever element it represents.
• Italics highlight technical terms when they appear for the first time in the text and
are sometimes used to emphasize important points.


What You’ll Learn in 24 Hours
Teach Yourself C in 24 Hours consists of five parts. In Part I, “The Basics of C,” you’ll
learn the basics of the C language. Here is a summary of what you’re going to learn:
Hour 1, “Taking the First Step,” introduces you to the C language, the ANSI standard, and the basic software and hardware requirements for C programming.
Hour 2, “Your First C Program,” demonstrates the entire procedure of writing,
compiling, linking, and running a C program.


×