logo资料库

Beginning C(5th) 无水印pdf.pdf

第1页 / 共675页
第2页 / 共675页
第3页 / 共675页
第4页 / 共675页
第5页 / 共675页
第6页 / 共675页
第7页 / 共675页
第8页 / 共675页
资料共675页,剩余部分请下载后查看
Cover
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
1: Programming in C
The C Language
The Standard Library
Learning C
Creating C Programs
Editing
Compiling
Linking
Executing
Creating Your First Program
Editing Your First Program
Dealing with Errors
Dissecting a Simple Program
Comments
Preprocessing Directives
Defining the main() Function
Keywords
The Body of a Function
Outputting Information
Function Arguments
Control Characters
Trigraph Sequences
The Preprocessor
Developing Programs in C
Understanding the Problem
Detailed Design
Implementation
Testing
Functions and Modular Programming
Common Mistakes
Points to Remember
Summary
2: First Steps in Programming
Memory in Your Computer
What Is a Variable?
Naming Variables
Variables That Store Integers
Using Variables
Initializing Variables
Basic Arithmetic Operations
More on Division with Integers
Unary Operators
Unary Minus Operator
Variables and Memory
Signed Integer Types
Unsigned Integer Types
Specifying Integer Constants
Hexadecimal Constants
Octal Constants
Default Integer Constant Types
Working with Floating-Point Numbers
Floating-Point Number Representation
Floating-Point Variables
Division Using Floating-Point Values
Controlling the Number of Decimal Places in the Output
Controlling the Output Field Width
More Complicated Expressions
Defining Named Constants
Knowing Your Limitations
Introducing the sizeof Operator
Choosing the Correct Type for the Job
Explicit Type Conversion
Automatic Conversions
Rules for Implicit Conversions
Implicit Conversions in Assignment Statements
More Numeric Data Types
Character Type
Character Input and Character Output
Enumerations
Choosing Enumerator Values
Unnamed Enumeration Types
Variables That Store Boolean Values
The op= Form of Assignment
Mathematical Functions
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Summary
3: Making Decisions
The Decision-Making Process
Arithmetic Comparisons
The Basic if Statement
Extending the if statement: if-else
Using Blocks of Code in if Statements
Nested if Statements
Testing Characters
Logical Operators
The AND Operator &&
The OR Operator ||
The NOT Operator!
The Conditional Operator
Operator Precedence: Who Goes First?
Multiple-Choice Questions
Using else-if Statements for Multiple Choices
The switch Statement
The goto Statement
Bitwise Operators
The op= Use of Bitwise Operators
Using Bitwise Operators
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Steps 3 and 4
Summary
4: Loops
How Loops Work
Introducing the Increment and Decrement Operators
The for Loop
General Form of the for Loop
More on the Increment and Decrement Operators
The Increment Operator
The Prefix and Postfix Forms of the Increment Operator
The Decrement Operator
The for Loop Revisited
Modifying the for Loop Control Variable
A for Loop with No Parameters
The break Statement in a Loop
Limiting Input Using a for Loop
Generating Pseudo-Random Integers
More for Loop Control Options
Floating-Point Loop Control Variables
The while Loop
Nested Loops
Nested Loops and the goto Statement
The do-while Loop
The continue Statement
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Step 4
Step 5
Summary
5: Arrays
An Introduction to Arrays
Programming Without Arrays
What Is an Array?
Using an Array
The Address of Operator
Arrays and Addresses
Initializing an Array
Finding the Size of an Array
Multidimensional Arrays
Initializing Multidimensional Arrays
Variable Length Arrays
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Step 4
Summary
6: Applications with Strings and Text
What Is a String?
Variables That Store Strings
Arrays of Strings
Operations with Strings
Checking for C11 Support
Finding the Length of a String
Copying Strings
Concatenating Strings
Comparing Strings
Searching a String
The Idea of a Pointer
Searching a String for a Character
Searching a String for a Substring
Tokenizing a String
Reading Newline Characters into a String
Analyzing and Transforming Strings
Converting Character Case
Converting Strings to Numerical Values
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Summary
7: Pointers
A First Look at Pointers
Declaring Pointers
Accessing a Value Through a Pointer
Using Pointers
Testing for a NULL Pointer
Pointers to Constants
Constant Pointers
Naming Pointers
Arrays and Pointers
Multidimensional Arrays
Multidimensional Arrays and Pointers
Accessing Array Elements
Using Memory As You Go
Dynamic Memory Allocation: The malloc() Function
Releasing Dynamically Allocated Memory
Memory Allocation with the calloc() Function
Extending Dynamically Allocated Memory
Handling Strings Using Pointers
Using Arrays of Pointers
Pointers and Array Notation
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
The Complete Program
Summary
8: Structuring Your Programs
Program Structure
Variable Scope and Lifetime
Variable Scope and Functions
Functions
Defining a Function
Naming a Function
Function Parameters
Specifying the Return Value Type
The return Statement
The Pass-By-Value Mechanism
Function Prototypes
Pointers as Parameters and Return Types
const Parameters
Perils of Returning Pointers
Summary
9: More on Functions
Pointers to Functions
Declaring a Pointer to a Function
Calling a Function Through a Function Pointer
Arrays of Pointers to Functions
Pointers to Functions As Arguments
Variables in Functions
Static Variables: Keeping Track Within a Function
Sharing Variables Between Functions
Functions That Call Themselves: Recursion
Functions with a Variable Number of Arguments
Copying a va_list
Basic Rules for Variable-Length Argument Lists
The main() Function
Terminating a Program
The abort() Function
The exit() and atexit() Functions
The _Exit() Function
The quick_exit() and at_quick_exit() Functions
Enhancing Performance
Declaring Functions Inline
Using the restrict Keyword
The _Noreturn Function Specifier
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Step 4
Summary
10: Essential Input and Output
Input and Output Streams
Standard Streams
Input from the Keyboard
Formatted Keyboard Input
Input Format Control Strings
Characters in the Input Format String
Variations on Floating-Point Input
Reading Hexadecimal and Octal Values
Reading Characters Using scanf_s()
String Input from the Keyboard
Single Character Keyboard Input
Output to the Screen
Formatted Output Using printf_s()
Escape Sequences
Integer Output
Outputting Floating-Point Values
Character Output
Other Output Functions
Unformatted Output to the Screen
Formatted Output to an Array
Formatted Input from an Array
Summary
11: Structuring Data
Data Structures: Using struct
Defining Structure Types and Structure Variables
Accessing Structure Members
Unnamed Structures
Arrays of Structures
Structure Members in Expressions
Pointers to Structures
Dynamic Memory Allocation for Structures
More on Structure Members
Structures As Members of a Structure
Declaring a Structure Within a Structure
Pointers to Structures As Structure Members
Doubly Linked Lists
Bit Fields in a Structure
Structures and Functions
Structures As Arguments to Functions
Pointers to Structures As Function Arguments
Structure As a Function Return Value
Binary Trees
Ordering Data in a Binary Tree
Constructing a Binary Tree
Traversing a Binary Tree
Sharing Memory
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Step 4
Summary
12: Working with Files
The Concept of a File
Positions in a File
File Streams
Accessing Files
Opening a File
Write Mode
Append Mode
Read Mode
Buffering File Operations
Renaming a File
Closing a File
Deleting a File
Writing a Text File
Reading a Text File
Reading and Writing Strings to a Text File
Formatted File Input and Output
Formatted Output to a File
Formatted Input from a File
Dealing with Errors
More Open Modes for Text Files
The freopen_s() Function
Binary File Input and Output
Opening a File in Binary Mode
Writing a Binary File
Reading a Binary File
Moving Around in a File
File Positioning Operations
Finding Out Where You Are
Setting a Position in a File
Using Temporary Work Files
Creating a Temporary Work File
Creating a Unique File Name
Updating Binary Files
Changing the Contents of a File
Creating a Record from Keyboard Input
Writing a Record to a File
Reading a Record from a File
Writing a File
Listing the File Contents
Updating the Existing File Contents
File Open Modes Summary
Designing a Program
The Problem
The Analysis
The Solution
Step 1
Step 2
Step 3
Summary
13: The Preprocessor and Debugging
Preprocessing
Including Header Files
Defining Your Own Header Files
Managing Multiple Source Files
External Variables
Static Functions
Substitutions in Your Program Source Code
Macros
Macros That Look Like Functions
Strings As Macro Arguments
Joining Two Arguments in a Macro Expansion
Preprocessor Directives on Multiple Lines
Logical Preprocessor Directives
Conditional Compilation
Testing for Multiple Conditions
Undefining Identifiers
Testing for Specific Values for Identifiers
Multiple-Choice Selections
Standard Preprocessing Macros
Debugging Methods
Integrated Debuggers
The Preprocessor in Debugging
Assertions
Runtime Assertions
Switching Off Assertions
Compile-Time Assertions
Date and Time Functions
Getting Time Values
Getting the Date
Getting the Day for a Date
Summary
14: Advanced and Specialized Topics
Working with International Character Sets
Understanding Unicode
Setting the Locale
The Wide Character Type wchar_t
Storing Wide Characters
Operations on Wide Characters
Working with Wide Character Strings
Operations on Wide Character Strings
File Stream Operations with Wide Characters
Fixed Size Types That Store Unicode Characters
Specialized Integer Types for Portability
Fixed Width Integer Types
Minimum Width Integer Types
Maximum Width Integer Types
The Complex Number Types
Complex Number Basics
Complex Types and Operations
Programming with Threads
Creating a Thread
Exiting a Thread
Joining One Thread to Another
Suspending a Thread
Managing Thread Access to Data
Creating a Mutex
Acquiring a Mutex
Releasing a Mutex
Summary
Appendix A: Computer Arithmetic
Binary Numbers
Hexadecimal Numbers
Negative Binary Numbers
Big-Endian and Little-Endian Systems
Floating-Point Numbers
Appendix B: ASCII Character Code Definitions
Appendix C: Reserved Words in C
Appendix D: Input and Output Format Specifications
Output Format Specifications
Input Format Specifications
Appendix E: Standard Library Header Files
Index
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
Contents at a Glance About the Author ��������������������������������������������������������������������������������������������������������������� xxi About the Technical Reviewer ����������������������������������������������������������������������������������������� xxiii Acknowledgments ������������������������������������������������������������������������������������������������������������ xxv Introduction �������������������������������������������������������������������������������������������������������������������� xxvii ■ Chapter 1: Programming in C ��������������������������������������������������������������������������������������������1 ■ Chapter 2: First Steps in Programming ���������������������������������������������������������������������������25 ■ Chapter 3: Making Decisions �������������������������������������������������������������������������������������������85 ■ Chapter 4: Loops ������������������������������������������������������������������������������������������������������������135 ■ Chapter 5: Arrays ����������������������������������������������������������������������������������������������������������185 ■ Chapter 6: Applications with Strings and Text ��������������������������������������������������������������219 ■ Chapter 7: Pointers ��������������������������������������������������������������������������������������������������������263 ■ Chapter 8: Structuring Your Programs ��������������������������������������������������������������������������321 ■ Chapter 9: More on Functions ���������������������������������������������������������������������������������������349 ■ Chapter 10: Essential Input and Output �������������������������������������������������������������������������395 ■ Chapter 11: Structuring Data �����������������������������������������������������������������������������������������429 ■ Chapter 12: Working with Files �������������������������������������������������������������������������������������489 ■ Chapter 13: The Preprocessor and Debugging ��������������������������������������������������������������557 ■ Chapter 14: Advanced and Specialized Topics ��������������������������������������������������������������589 v
■ Contents at a GlanCe ■ Appendix A: Computer Arithmetic ���������������������������������������������������������������������������������621 ■ Appendix B: ASCII Character Code Definitions ��������������������������������������������������������������629 ■ Appendix C: Reserved Words in C ����������������������������������������������������������������������������������635 ■ Appendix D: Input and Output Format Specifications ����������������������������������������������������637 ■ Appendix E: Standard Library Header Files �������������������������������������������������������������������643 Index ���������������������������������������������������������������������������������������������������������������������������������645 vi
Introduction Welcome to Beginning C: Fifth Edition. With this book you can become a competent C programmer using the latest version of the C language. In many ways, C is an ideal language with which to learn programming. It’s very compact, so there isn’t a lot of syntax to learn before you can write real applications. In spite of its conciseness, it’s extremely powerful and is used by professionals in many different areas. The power of C is such that it can be applied at all levels, from developing device drivers and operating system components to creating large-scale applications. A relatively new area for C is in application development for mobile phones. C compilers are available for virtually every kind of computer, so when you’ve learned C, you’ll be equipped to program in just about any context. Once you know C, you have an excellent base from which you can build an understanding of the object-oriented C++. My objective in this book is to minimize what I think are the three main hurdles the aspiring programmer must face: coming to grips with the jargon that pervades every programming language, understanding how to use the language elements (as opposed to merely knowing what they are), and appreciating how the language is applied in a practical context. Jargon is an invaluable and virtually indispensable means of communication for the expert professional as well as the competent amateur, so it can’t be avoided. My approach is to ensure that you understand the jargon and get comfortable using it in context. In this way, you’ll be able to more effectively use the documentation that comes along with the typical programming product and also feel comfortable reading and learning from the literature that surrounds most programming languages. Comprehending the syntax and effects of the language elements is obviously an essential part of learning C, but appreciating how the language features work and how they are used is equally important. Rather than just using code fragments, I provide you with practical working examples in each chapter that show how the language features can be applied to specific problems. These examples provide a basis for you to experiment and see the effects of changing the code. Your understanding of programming in context needs to go beyond the mechanics of applying individual language elements. To help you gain this understanding, I conclude most chapters with a more complex program that applies what you’ve learned in the chapter. These programs will help you gain the competence and confidence to develop your own applications and provide you with insight into how you can apply language elements in combination and on a larger scale. Most important, they’ll give you an idea of what’s involved in designing real programs and managing real code. It’s important to realize a few things that are true for learning any programming language. First, there is quite a lot to learn, but this means you’ll gain a greater sense of satisfaction when you’ve mastered it. Second, it’s great fun, so you really will enjoy it. Third, you can only learn programming by doing it, and this book helps you along the way. Finally, it’s certain you will make a lot of mistakes and get frustrated from time to time during the learning process. When you think you are completely stuck, you just need to be persistent. You will eventually experience that eureka moment and realize it wasn’t as difficult as you thought. xxvii
■ IntroduCtIon How to Use This Book Because I believe in the hands-on approach, you’ll write your first programs almost immediately. Every chapter has several complete programs that put theory into practice, and these are key to the book. You should type in and run all the examples that appear in the text because the very act of typing them in is a tremendous memory aid. You should also attempt all the exercises that appear at the end of each chapter. When you get a program to work for the first time—particularly when you’re trying to solve your own problems—you’ll find that the great sense of accomplishment and progress makes it all worthwhile. The pace is gentle at the start, but you’ll gain momentum as you get further into the subject. Each chapter covers quite a lot of ground, so take your time and make sure you understand everything before moving on. Experimenting with the code and trying out your own ideas are important parts of the learning process. Try modifying the programs and see what else you can make them do—that’s when it gets really interesting. And don’t be afraid to try things out—if you don’t understand how something works, just type in a few variations and see what happens. It doesn’t matter if it’s wrong. You’ll find you often learn a lot from getting it wrong. A good approach is to read each chapter through, get an idea of its scope, and then go back and work through all the examples. You might find some of the end-of-chapter programs quite difficult. Don’t worry if it’s not all completely clear on the first try. There are bound to be bits that you find hard to understand at first because they often apply what you’ve learned to rather complicated problems. If you really get stuck, you can skip the end-of-chapter exercises, move on to the next chapter, and come back to them later. You can even go through the entire book without worrying about them. However, if you can complete the exercises, it shows you are making real progress. Who This Book Is For Beginning C: Fifth Edition is designed to teach you how to write useful programs in C as quickly and easily as possible. By the end of Beginning C, you’ll have a thorough grounding in programming the C language. This is a tutorial for those who’ve done a little bit of programming before, understand the concepts behind it, and want to further your knowledge by learning C. However, no previous programming knowledge on your part is assumed, so if you’re a newcomer to programming, the book will still work for you. What You Need to Use This Book To use this book, you’ll need a computer with a C compiler and library installed, so you can execute the examples, and a program text editor for preparing your source code files. The compiler you use should provide good support for the current International Standard for the C language, ISO/IEC 9899:2011, commonly referred to as C11. You’ll also need an editor for creating and modifying your code. You can use any plain text editor such as Notepad or vi to create your source program files. However, you’ll get along better if your editor is designed for editing C code. I can suggest two sources for a suitable C compiler, both of which are freeware: • • The GNU C compiler, GCC, is available from operating system environments. http://www.gnu.org and supports a variety of The Pelles C compiler for Microsoft Windows is downloadable from http://www.smorgasbordet.com/pellesc/ and includes an excellent IDE. xxviii
Conventions Used I use a number of different styles of text and layout in the book to help differentiate between the different kinds of information. For the most part, their meanings will be obvious. Program code will appear like this: ■ IntroduCtIon int main(void) { printf("Beginning C\n"); return 0; } When a code fragment is a modified version of a previous instance, I occasionally show the lines that have changed in bold type like this: int main(void) { printf("Beginning C by Ivor Horton\n"); return 0; } When code appears in the text, it has a different typestyle that looks like this: double. I’ll use different types of “brackets” in the program code. They aren’t interchangeable, and their differences are very important. I’ll refer to the symbols ( ) as parentheses, the symbols { } as braces, and the symbols [ ] as square brackets. Important new words in the text are shown in italic like this. xxix
Chapter 1 Programming in C C is a powerful and compact computer language that allows you to write programs that specify exactly what you want your computer to do. You’re in charge: you create a program, which is just a set of instructions, and your computer will follow them. Programming in C isn’t difficult, as you’re about to find out. I’m going to teach you all the fundamentals of C programming in an enjoyable and easy-to-understand way, and by the end of this chapter you’ll have written your first few C programs. It’s as easy as that! In this chapter you’ll learn: • • • • • What the C language standard is What the standard library is How to create C programs How C programs are organized How to write your own program to display text on the screen The C Language C is remarkably flexible. It has been used for developing just about everything you can imagine by way of a computer program, from accounting applications to word processing and from games to operating systems. It is not only the basis for more advanced languages, such as C++, it is also used currently for developing mobile phone apps in the form of Objective C. Objective C is standard C with a thin veneer of object-oriented programming capability added. C is easy to learn because of its compactness. Thus, C is an ideal first language if you have ambitions to be a programmer. You’ll acquire sufficient knowledge for practical application development quickly and easily. The C language is defined by an international standard, and the latest is currently defined by the document ISO/IEC 9899:2011. The current standard is commonly referred to as C11, and the language that I describe in this book conforms to C11. You need to be aware that some elements of the language as defined by C11 are optional. This implies that a C compiler that conforms to the C11 standard may not implement everything in the standard. (A compiler is just a program that converts your program written in terms you understand into a form your computer understands.) I will identify any language feature in the book that is optional so far as C11 is concerned, just so you are aware that it is possible that your compiler may not support it. It is also possible that a C11 compiler may not implement all of the language features mandated by the C11 standard. It takes time to implement new language capabilities, so compiler developers will often take an incremental approach to implementing them. This provides another reason why a program may not work. Having said that, I can confirm from my own experience that the most common reason for things not working in a C program, at least 99.9% of the time, is that a mistake has been made. 1
分享到:
收藏