You are previewing Head First C.
O'Reilly logo
Head First C

Book Description

Head First C provides a complete learning experience for C and structured imperative programming. With a unique method that not only goes beyond syntax and how-to manuals, this guide not only teaches you the language, it helps you understand how to be a great programmer. You’ll learn key areas such as language basics, pointers and pointer arithmetic, and dynamic memory management. Advanced topics include multi-threading and network programming.

Table of Contents

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