Home Page Icon
Home Page
Table of Contents for
Dedication
Close
Dedication
by Dawn Griffiths, David Griffiths
Head First C
Dedication
Advance Praise for Head First C
Praise for other Head First books
Authors of Head First C
How to use this Book: Intro
Who is this book for?
Who should probably back away from this book?
We know what you’re thinking
We know what your brain is thinking
Metacognition: thinking about thinking
Here’s what WE did
Here’s what YOU can do to bend your brain into submission
Read me
The technical review team
Acknowledgments
Safari® Books Online
1. Getting Started with C: Diving in
C is a language for small, fast programs
The way C works
But what does a complete C program look like?
But how do you run the program?
The program works!
Two types of command
Do something
Do something only if something is true
Here’s the code so far
Card counting? In C?
There’s more to booleans than equals...
&& checks if two conditions are true
II checks if one of two conditions is true
! flips the value of a condition
What’s the code like now?
Pulling the ol’ switcheroo
Sometimes once is not enough...
Using while loops in C
Loops often follow the same structure...
...and the for loop makes this easy
You use break to break out...
...and continue to continue
Your C Toolbox
2. Memory and Pointers: What are you pointing at?
C code includes pointers
Digging into memory
Set sail with pointers
Set sail sou’east, Cap’n
Try passing a pointer to the variable
Pointers make it easier to share memory
Using memory pointers
How do you pass a string to a function?
Honey, who shrank the string?
Array variables are like pointers...
...so our function was passed a pointer
What the computer thinks when it runs your code
But array variables aren’t quite pointers
Why arrays really start at 0
Why pointers have types
Using pointers for data entry
Entering numbers with scanf()
Be careful with scanf()
scanf() can cause buffer overflows
fgets() is an alternative to scanf()
Using sizeof with fgets()
Anyone for three-card monte?
Oops...there’s a memory problem...
String literals can never be updated
If you’re going to change a string, make a copy
Memory memorizer
Your C Toolbox
2.5. Strings: String theory
Desperately seeking Susan Frank
Create an array of arrays
Find strings containing the search text
Using string.h
Using the strstr() function
It’s time for a code review
Array of arrays vs. array of pointers
Your C Toolbox
3. Creating Small Tools: Do one thing and do it well
Small tools can solve big problems
Here’s how the program should work
But you’re not using files...
You can use redirection
You can redirect the Standard Input with <...
...and redirect the Standard Output with >
But there’s a problem with some of the data...
Introducing the Standard Error
By default, the Standard Error is sent to the display
fprintf() prints to a data stream
Let’s update the code to use fprintf()
Small tools are flexible
Don’t change the geo2json tool
A different task needs a different tool
Connect your input and output with a pipe
The bermuda tool
But what if you want to output to more than one file?
Roll your own data streams
The program runs, but...
There’s more to main()
Overheard at the Head First Pizzeria
Let the library do the work for you
Your C Toolbox
4. Using Multiple Source Files: Break it down, build it up
Don’t put something big into something small
Use casting to put floats into whole numbers
Oh no...it’s the out-of-work actors...
Let’s see what’s happened to the code
Compilers don’t like surprises
Fixing function order is a pain
In some situations, there is no correct order
Split the declaration from the definition
Creating your first header file
If you have common features...
...it’s good to share code
You can split the code into separate files
Compilation behind the scenes
The shared code needs its own header file
Include encrypt.h in your program
It’s not rocket science...or is it?
Don’t recompile every file
Save copies of the compiled code
First, compile the source into object files
Then, link them together
It’s hard to keep track of the files
Automate your builds with the make tool
What does make need to know?
How make works
Tell make about your code with a makefile
Your C Toolbox
C Lab 1: Arduino
The spec: make your houseplant talk
The physical device
The Arduino
The Arduino IDE
Build the physical device
Build the moisture sensor
Connect the LED
Connect the moisture sensor
Here’s what your code should do
Read from the moisture sensor
Write to the LED
Write to the serial port
Here’s what your C code should look like
Here are some useful Arduino functions
The finished product
5. Structs, Unions, and Bitfields: Roll your own structures
Sometimes you need to hand around a lot of data
Cubicle conversation
Create your own structured data types with a struct
Just give them the fish
Read a struct’s fields with the “.” operator
Can you put one struct inside another?
How do you update a struct?
The code is cloning the turtle
You need a pointer to the struct
(*t).age vs. *t.age
Sometimes the same type of thing needs different types of data
A union lets you reuse memory space
How do you use a union?
C89 style for the first field
Designated initializers set other values
Set the value with dot notation
unions are often used with structs
An enum variable stores a symbol
Sometimes you want control at the bit level
Bitfields store a custom number of bits
Your C Toolbox
6. Data Structures and Dynamic Memory: Building bridges
Do you need flexible storage?
Linked lists are like chains of data
Linked lists allow inserts
Create a recursive structure
Create islands in C...
...and link them together to form a tour
Inserting values into the list
Use the heap for dynamic storage
First, get your memory with malloc()
Give the memory back when you’re done
Free memory by calling the free() function
Ask for memory with malloc()...
...and free up the memory with free()
Oh, no! It’s the out-of-work actors...
Let’s fix the code using the strdup() function
So does it fix the code?
Free the memory when you’re done
Exhibit A: the source code
An overview of the SPIES system
The program builds a tree of suspects
Software forensics: using valgrind
Prepare your code: add debug info
Just the facts: interrogate your code
Use valgrind repeatedly to gather more evidence
This time, valgrind found a memory leak
Look at the evidence
1. Location
2. Clues from valgrind
The fix on trial
The leak is fixed
Your C Toolbox
7. Advanced Functions: Turn your functions up to 11
Looking for Mr. Right...
Pass code to a function
You need to tell find() the name of a function
Every function name is a pointer to the function...
...but there’s no function data type
Why doesn’t C have a function data type?
How to create function pointers
Get it sorted with the C Standard Library
Use function pointers to set the order
Automating the Dear John letters
Create an array of function pointers
But how does an array help?
Make your functions streeeeeetchy
So how can YOU do that?
Your C Toolbox
8. Static and Dynamic Libraries: Hot-swappable code
Code you can take to the bank
Angle brackets are for standard headers
But what if you want to share code?
Sharing .h header files
Share .o object files by using the full pathname
An archive contains .o files
Create an archive with the ar command...
...then store the .a in a library directory
Finally, compile your other programs
The Head First Gym is going global
Calculating calories
But things are a bit more complex...
Programs are made out of lots of pieces...
...but once they’re linked, you can’t change them
Dynamic linking happens at runtime
Can you link .a at runtime?
Dynamic libraries are object files on steroids
First, create an object file
What you call your dynamic library depends on your platform
Compiling the elliptical program
Your C Toolbox
C Lab 2: OpenCV
The spec: turn your computer into an intruder detector
The intruder detector
OpenCV
Installing OpenCV
What your code should do
Take input from your computer camera
Grab an image from the webcam
Detect an intruder
Make a clean getaway
Optional: show the current webcam output
The finished product
It’s time to become a C ninja...
9. Processes and System Calls: Breaking boundaries
System calls are your hotline to the OS
Then someone busted into the system...
Security’s not the only problem
The exec() functions give you more control
exec() functions replace the current process
There are many exec() functions
The list functions: execl(), execlp(), execle()
The array functions: execv(), execvp(), execve()
Passing environment variables
But what if there’s a problem?
Most system calls go wrong in the same way
Read the news with RSS
exec() is the end of the line for your program
fork() will clone your process
Running a child process with fork() + exec()
1. Make a copy
2. If you’re the child process, call exec()
Your C Toolbox
10. Interprocess Communication: It’s good to talk
Redirecting input and output
A look inside a typical process
Redirection just replaces data streams
Processes can redirect themselves
fileno() tells you the descriptor
dup2() duplicates data streams
Sometimes you need to wait...
The waitpid() function
Stay in touch with your child
Reading story links from rssgossip
Connect your processes with pipes
Piped commands are parents and children
Case study: opening stories in a browser
pipe() opens two data streams
In the child
In the parent
Opening a web page in a browser
The death of a process
The O/S controls your program with signals
Catching signals and running your own code
A sigaction is a function wrapper
All handlers take signal arguments
sigactions are registered with sigaction()
Rewriting the code to use a signal handler
Use kill to send signals
Send signals with raise()
Sending your code a wake-up call
...the timer fires a SIGALRM signal
Your C Toolbox
11. Sockets and Networking: There’s no place like 127.0.0.1
The Internet knock-knock server
Knock-knock server overview
BLAB: how servers talk to the Internet
1. Bind to a port
2. Listen
3. Accept a connection
A socket’s not your typical data stream
Sometimes the server doesn’t start properly
Why your mom always told you to check for errors
Bound ports are sticky
Reading from the client
The server can only talk to one person at a time
You can fork() a process for each client
The parent and child use different sockets
Writing a web client
Clients are in charge
Remote ports and IP addresses
Create a socket for an IP address
getaddrinfo() gets addresses for domains
Create a socket for a domain name
Your C Toolbox
12. Threads: It’s a parallel world
Tasks are sequential...or not...
...and processes are not always the answer
Simple processes do one thing at a time
Employ extra staff: use threads
How do you create threads?
Create threads with pthread_create
The code is not thread-safe
You need to add traffic signals
Use a mutex as a traffic signal
Your C Toolbox
C Lab 3: Blasteroids
Write the arcade game Blasteroids
Your mission: blast the asteroids without getting hit
Allegro
Installing Allegro
You may need CMake
What does Allegro do for you?
Building the game
The spaceship
What the spaceship looks like
Collisions
Spaceship behavior
Reading keypresses
The blast
Blast appearance
Blast behavior
The asteroid
Asteroid appearance
How the asteroid moves
When the asteroid is hit by a blast
The game status
Use transformations to move things around
The finished product
Leaving town...
It’s been great having you here in Cville!
A. Leftovers: The top ten things (we didn’t cover)
#1. Operators
Increments and decrements
The ternary operator
Bit twiddling
Commas to separate expressions
#2. Preprocessor directives
Conditions
#3. The static keyword
static can also make things private
#4. How big stuff is
#5. Automated testing
#6. More on gcc
Optimization
Warnings
#7. More on make
Variables
Using %, ^, and @
Implicit rules
#8. Development tools
gdb
gprof
gcov
#9. Creating GUIs
Linux — GTK
Windows
The Mac — Carbon
#10. Reference material
Websites
B. C Topics: Revision roundup
Basics
Pointers and memory
Strings
Data streams
Data types
Multiple files
Structs
Unions and bitfields
Data structures
Dynamic memory
Advanced functions
Static and dynamic libraries
Processes and communication
Sockets and networking
Threads
Index
About the Authors
Copyright
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Prev
Previous Chapter
Head First C
Next
Next Chapter
Advance Praise for Head First C
To Dennis Ritchie (1941–2011), the father of C.
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset