09 - Debugging and Characters
09 - Debugging and Characters
Fundamentals
Week 5 - Lecture 9
What did we learn last week?
Functions
● Libraries
Arrays
● 2D Arrays
Pointers
Debugging
● What's a bug?
● How do we find them and remove them?
Characters
● It’s a variable that stores the address of another variable of a specific type
● We call them pointers because knowing something’s address allows you
to “point” at it
Why pointers?
int i = 100;
// create a pointer called ip that
// stores the address of i
int *ip = &i;
Using Pointers
If we want to look at the variable that a pointer “points at”
int i = 100;
// create a pointer called ip that points at
// the location of i
int *ip = &i;
printf("The value of the variable at %p is %d", ip, *ip);
Pointers in Functions
We'll often use pointers as input to functions
● What is a bug?
● Different types of bugs
● How to find bugs
● Syntax Errors
● Logical Errors
Syntax Errors
C is a specific language with its own grammar
● The simplest thing we can do is run dcc and see what happens
● Look for a line number and character (column) in the error message
● Sometimes knowing where it is is enough for you to solve it
What did we discover? (spoilers here . . . try debugging before reading this slide!)
● Single = if statement.
○ = is an assignment of a value
○ == is a relational operator
● An extra bracket causes a lot of issues (and a very odd error message)
Testing
We’ll often test parts of all of our code to make sure it’s working
Finding a needle in a haystack gets easier if you can split the haystack
into smaller parts!
Let’s try some information gathering
Some of the tricks we’ll use, continuing with our debugThis.c
Logical errors can be hard to find because the code looks correct syntactically
Characters
We’ve only used ints and doubles so far
Note the use of %c in the printf will format the variable as a character
Helpful Library Functions
getchar() is a function that will read a character from input
● Newline(\n) is a character
● Space is a character
● There’s also a special character, EOF (End of File) that signifies that there’s
no more input
● EOF has been #defined in stdio.h, so we use it like a constant
● We can signal the end of input in a Linux terminal by using Ctrl-D
Working with multiple characters
We can read in multiple characters (including space and newline)
This code is worth trying out . . . you get to see that space and newline have
ASCII codes!
// reading multiple characters in a loop
int readChar;
readChar = getchar();
while (readChar != EOF) {
printf(
"I read character: %c, with ASCII code: %d.\n",
readChar, readChar
);
readChar = getchar();
}
More Character Functions
<ctype.h> is a useful library that works with characters
● There are more! Look up ctype.h references or man pages for more
information
What did we learn today?
Pointers Recap
Debugging
Characters