Professional Documents
Culture Documents
Advanced C
Student Workbook
py
Co
.
ard
a rew
or
2f
on
65
2-2
-29
00
ll 8
ati
ca
se
lea
,p
ok
bo
ork
sw
alu
thi
old
ns
ee
eb
av
rh
Ev
,o
ok
bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
2 Advanced C Programming
Advanced C Programming
Jeff Howell
Published by itcourseware, 10333 E. Dry Creek Rd., Suite 150, Englewood, CO 80112
If y
Ev
Special thanks to: Many instructors whose ideas and careful review have contributed to the
ou
quality of this workbook, including Brandon Caldwell, Denise Geller, Todd Gibson, Roger
are
Jones, Channing Lovely, and Danielle Waleri, and the many students who have offered
be
alu
Copyright © 1994-1999 by itcourseware, Inc. All rights reserved. No part of this book may
to
f th
ati
writing from the publisher. Inquiries should be addressed to it courseware, Inc., 10333 E. Dry
bo
All brand names, product names, trademarks, and registered trademarks are the property of
eb
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Contents
Ev
Chapter 1 - Course Introduction ............................................................................................. 7
If y
alu
Chapter 2 - The C Development Evnironment ...................................................................... 15
gh
t
Include Files................................................................................................................... 21
is w
Libraries ........................................................................................................................ 23
ork
ati
bo
Exercises ...................................................................................................................... 25
ok
,o
rh
on
Chapter Objectives ........................................................................................................ 29
ee
ns
Co
Structure Data Types...................................................................................................... 41
,p
lea
Using typedef................................................................................................................. 53
65
2f
Exercises ...................................................................................................................... 55
or
Appendix ....................................................................................................................... 57
a
rew
ard
File Access.................................................................................................................... 77
are
Formatted I/O................................................................................................................. 79
be
ing
alu
String I/O ........................................................................................................................ 81
tau
Exercises ...................................................................................................................... 87
to
f th
is w
ati
bo
File Access.................................................................................................................... 99
av
eb
Co
,p
alu
Debugging Techniques ................................................................................................ 155
gh
ati
bo
ok
Co
,p
old
ns
ee
eb
av
rh
ati
bo
ok
,o
rh
av
eb
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
ee
eb
av
rh
Ev
,o
ok
Chapter Objectives
Ev
Create structure types and variables.
ou
are
be
alu
Declare and use pointers to simple data types.
out
to
f th
ati
Use operators to mask bits.
bo
ok
,o
rh
on
ee
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
ee
eb
av
rh
Ev
,o
ok
alu
for the object.
tau
gh
They also define the set of legal values and operations that may
out
ati
Integral (fixed point)
bo
- Integers (int)
ok
,o
- Characters (char)
rh
av
- Enumerated (enum)
eb
on
ee
Floating Point
ns
old
- Float (float)
thi
- Double (double)
sw
ork
bo
All other types (user-defined) are derived from the two basic C types.
ok
Co
,p
lea
Arrays
se
ca
Structures
ll 8
00
Pointers
-29
py
2-2
65
2f
Notes
Enumerated values make code more readable, and therefore more maintainable.
An an example:
Ev
main()
{
If y
alu
enum orange_types orange;
tau
gh
t
switch (orange)
to
f th
{
is w
case VALENCIA:
ork
ati
printf ("Just right.\n");
bo
break;
ok
,o
case TANGERINE:
rh
break;
eb
on
ee
case NAVEL:
ns
break;
thi
default:
sw
break;
bo
ok
Co
}
,p
apple = orange;
ll 8
}
00
-29
displays:
py
2-2
Just right.
65
Too sour.
2f
Too pulpy.
or
a
Is it seedless anyway?
rew
ard
In the example, orange can be compared against the “readable” values VALENCIA,
.
TANGERINE and NAVEL. Enumerated types assist in readability, but note that they do not
restrict objects of that type from taking on values outside the enumerated type.
Ev
The following are integral type object declarations:
alu
short sivar = -10; /* typically 2 bytes */
tau
ati
(e.g.: ASCII).
bo
ok
,o
rh
on
ee
ns
Co
,p
lea
py
2-2
associates RED with 0, YELLOW with 42, and GREEN with 43.
a
rew
ard
.
Notes
Because floats are not exact numbers, keep in mind the level of accuracy when displaying
floating pointing results.
Ev
For an (exaggerated) example, the following program:
If y
{
are
double pi = 3.14159;
be
ing
tau
alu
/* attempt to print 16 significant digits */
gh
}
to
f th
is w
ati
bo
Since we defined pi with only 5 significant digits, no more than 5 should be printed.
av
eb
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Ev
The following are floating point type object declarations:
ou
are
be
alu
double dvar = 42e102; /* typically 8 bytes */
tau
gh
out
to
f th
is w
ork
ati
bo
ok
,o
rh
av
eb
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
ee
eb
av
rh
Ev
,o
ok
alu
Arrays, structures, and pointers are some of the more common
tau
gh
derived types.
out
to
f th
ati
bo
ok
,o
rh
av
eb
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Notes
You may have an array of any like-typed objects, including an array of arrays. N-dimensional arrays
are specified by appending additional bracket pairs to a one-dimensional array.
N-dimensional arrays may be initialized by specifying a value for each element. The following may
be
alu
int num_array [2][3] = { 0, 1, 2, 3, 4, 5};
gh
out
Though the array elements are stored contiguously in memory, it may be easier to think of a 2-
to
dimensional array as having rows and columns. num_array can be thought of as having 2 rows,
f th
is w
ati
bo
You may omit the size of the first dimension on array initializations. All other dimensions must be
rh
av
specified. If present, the compiler uses the number of inner brace pairs to determine the first
eb
dimension of the array. Otherwise, the elements are assigned one by one to each of the specified
on
ee
ns
If there aren’t as many initializing values as are elements in the array, the remaining elements are
bo
Co
,p
lea
54,0,0,0,
ca
ll 8
55,56,57,58,
00
-29
60,1,2,3,
py
2-2
64,5,6,0,
65
68,9,0,0};
2f
or
a
rew
{54},
.
{55,56,57,58}},
{{60,1,2,3},
{64,5,6},
{68,9}}};
Ev
Simple array type objects are declared as:
are
be
ing
alu
type var_identifier [dim] [= {initializers}];
tau
gh
t
ati
bo
ok
,o
on
ee
ns
old
Co
,p
lea
The array name itself is a constant pointer to the base element of the
py
2-2
ee
eb
av
rh
Ev
,o
ok
structures.
ou
are
be
alu
struct [tag] {
tau
gh
type var_identifier;
out
...
to
f th
} [struct_var_identifier];
is w
ork
ati
bo
For example:
ok
,o
rh
struct personnel {
av
eb
int age;
old
} exempt;
ork
structure type.
00
py
2-2
65
exempt.age = 45;
strcpy (exempt.name, "Fredina");
temps [0].age = 45;
Notes
Pointers may be declared to be of any type. A pointer is scaled according to its type.
Scaling allows pointer arithmetic.
Ev
For example:
If y
int i;
ou
alu
for (i = 0; i<3; i++)
tau
*pi++ = i;
gh
out
ati
bo
Why?
ok
,o
rh
Because the compiler uses the type pointed to for scaling information, once declared as a
av
eb
certain type, you should not assign a pointer of one type to a pointer of another.
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Ev
- The address of an object is obtained with the & operator.
ou
are
be
alu
Objects are indirectly referenced through pointers.
out
to
f th
ati
type * pvar [= initializer];
bo
ok
,o
rh
on
ee
Co
,p
lea
Notes
You may declare a pointer to any type, including to another pointer. Using the declarations
on the following page, we may define the following:
Ev
struct student_info student;
struct student_info *ptr_student = &student;
If y
alu
student <
out
to
f th
is w
ork
ati
ptr_student &student
bo
<
ok
,o
rh
av
eb
ptr_ptr_student &ptr_student
on
ee
ns
old
thi
sw
student.name
Co
,p
ptr_student->ssn
lea
(*(*ptr_ptr_student)).address
se
ca
(*ptr_ptr_student)->address
ll 8
00
-29
Remember that array notation may be used to dereference a pointer. The last example
py
2-2
Ev
struct name *pstr [= initializer];
alu
struct student_info {
gh
t
long ssn;
f th
is w
float gpa;
ork
ati
char address [50];
bo
} senior, graduate;
ok
,o
rh
av
on
ee
ns
(*pstr_stu).gpa = senior.gpa;
bo
ok
Co
,p
notation:
ca
pstr_stu->gpa = senior.gpa;
ll 8
00
-29
py
2-2
Notes
1) You can’t pass a function argument to another function, but you can pass
Ev
a function pointer to another function.
2) You can’t store a function in a structure or array type, but you can store
If y
For example, every sort routine is basically the same: compare two values, if one is
be
ing
greater than the other then swap them. It doesn’t matter if the value types are integer, float
tau
alu
or string. The logic is the same. However, without the use of function pointers, each type
gh
of value would require a separate swap function, expecting arguments of that type. Using
out
function pointers allows you to use one swap function to handle all different type values
to
f th
ati
Arrays of function pointers are commonly used. Here is a brief example of an array of
bo
function pointers:
ok
,o
rh
main()
av
eb
{
on
ee
int i;
ns
Co
}
ca
{
00
-29
}
65
{
or
a
}
ard
.
Pointers to Functions
alu
an int.
tau
Also like arrays, function names are constant pointers and can
gh
out
not be reassigned.
to
f th
ati
bo
ptr_func = myfunc;
ok
,o
function myfunc.
on
ee
ns
main()
sw
{
ork
int result;
lea
se
ca
result = func_select[0]();
ll 8
result = func_select[1]();
py
2-2
}
2f
or
{
ard
return 42;
.
}
int fn1 (void)
{
return 52;
}
© 1994-1999 by it courseware, Inc. 8/99
48 Advanced C Programming
Notes
Use const freely to protect yourself from unwanted, unexpected changes. When passing
pointers to functions, referenced values are always in danger of being accidentally
modified. You may protect values from accidental changes by declaring const formal
Ev
parameters. Attempts to change constant values will be caught at compile time.
If y
For example:
ou
are
alu
main()
tau
{
gh
int a = 42;
out
b(&a);
is w
ati
}
bo
{
rh
(*a)++; /* ERROR */
av
eb
}
on
ee
ns
old
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Examples:
are
be
ing
alu
void *strcpy (char *target, const char *source);
tau
gh
or equivalently
out
ati
bo
on
ee
ns
Co
,p
lea
py
2-2
65
2f
or
a
rew
ard
.
Notes
You may also use bit representations to pack data. For example, if you had to keep information on employees
(e.g.: id, years of service and department number), you would probably use a structure:
struct employees {
int id;
int yrs;
Ev
int dept_no};
If y
Suppose that the id <= 63, the years of service <= 31 and the department number <= 31. Then the
ou
ID Years Department No
ing
alu
xxxxxx xxxxx xxxxx
tau
gh
The following code will store all the input data into a short integer, and will then unpack the data for display:
out
#include <stdio.h>
to
void main(void)
f th
{
is w
ati
void unmask (unsigned short emp,
bo
on
unsigned int id, dept_no, yrs;
ee
ns
fflush (stdin);
bo
ok
Co
employee |= id;
lea
}
2f
{
/* mask the bits, and reset (shift) to original value */
*id = (int)(emp & 0xfc00)>>10;
*yrs = (int)(emp &0x03e0)>>5;
*dept_no = (int)(emp &0x001f);
}
© 1994-1999 by it courseware, Inc. 8/99
Chapter 3 Basic and Derived Data Types in C 51
Bit Operators
~ (complement) | (or)
Ev
& (and) << (left shift)
If y
alu
The arguments are treated as strings of zeroes and ones.
tau
gh
Examples:
out
to
f th
ati
2 00000000 00000000 00000000 00000010
bo
ok
,o
rh
You can use the bit operators to extract bits from a variable.
ok
Co
,p
For example, to verify that a number is odd, you need only status the
se
ca
Notes
The typedef facility promotes self-documenting code. Compare the two code fragments
below.
Ev
float length, width; versus typedef float FEET;
FEET length, width;
If y
ou
The typedef makes the unit of measure implicit. Long, cumbersome declarations can be
are
alu
typedef struct {
gh
string fname;
out
string lname;
to
f th
FEET height;
is w
}student;
ork
ati
bo
on
ee
ns
old
thi
sw
ork
bo
ok
Co
,p
lea
se
ca
ll 8
00
-29
py
2-2
65
2f
or
a
rew
ard
.
Using typedef
You may create an alias for a type name using C’s typedef
facility. Ev
typedef type newname;
If y
ou
typedef does not create a new type, only another name for an
are
be
existing type.
ing
tau
gh
alu
For example:
out
to
f th
ati
bo
ok
creates an additional name for the type char * and creates two
,o
rh
string objects.
av
eb
on
ee
vector array;
thi
...
sw
ork
array[0] = 42;
bo
ok
Co
,p
py
2-2
65
2f
or
a
rew
ard
.
ee
eb
av
rh
Ev
,o
ok
Exercises
q - Quit
be
ing
alu
Implement these options as described in the following exercises:
tau
gh
2) Option e:
out
to
Prompt a user to enter an employee’s name, id, department number and age.
f th
ati
3) Option a:
bo
ok
4) Option q:
eb
Optional
thi
sw
ork
A) Option d:
bo
Co
,p
Search the array. If found, display the employee. If not found, allow the user
lea
py
2-2
65
2f
or
a
rew
ard
.
ee
eb
av
rh
Ev
,o
ok
Appendix
#include <stdio.h>
#include <stdlib.h>
{
int i;
be
ing
employee emp[2];
out
ati
compare = name_compare;
bo
}
se
{
ll 8
} /* name_compare */
-29
{
65
} /* age_compare */
or
{
rew
employee temp;
/* compare function called depends on which was sent in */
ard
{
temp = v[0];
v[0] = v[1];
v[1] = temp;
}
} /* swap */
ee
eb
av
rh
Ev
,o
ok