Vous êtes sur la page 1sur 38

Programming

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

comments, suggestions, criticisms, and insights.


ing
tau
gh
out

alu
Copyright © 1994-1999 by itcourseware, Inc. All rights reserved. No part of this book may
to
f th

be reproduced or utilized in any form or by any means, electronic or mechanical, including


is w

photo-copying, recording, or by an information storage retrieval system, without permission in


ork

ati
writing from the publisher. Inquiries should be addressed to it courseware, Inc., 10333 E. Dry
bo

Creek Rd., Suite 150, Englewood, Colorado, 80112. (303) 874-1099.


ok
,o
rh
av

All brand names, product names, trademarks, and registered trademarks are the property of
eb

their respective owners.


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
.

© 1994-1999 by it courseware, Inc. 8/99


Advanced C Programming 3

Contents
Ev
Chapter 1 - Course Introduction ............................................................................................. 7
If y

Course Objectives ........................................................................................................... 9


ou

Course Overview ........................................................................................................... 11


are

Suggested References .................................................................................................. 13


be
ing
tau

alu
Chapter 2 - The C Development Evnironment ...................................................................... 15
gh
t

Chapter Objectives ........................................................................................................ 17


ou
to

The cc (1) Command ..................................................................................................... 19


f th

Include Files................................................................................................................... 21
is w

Libraries ........................................................................................................................ 23
ork

ati
bo

Exercises ...................................................................................................................... 25
ok
,o
rh

Chapter 3 - Basic and Derived Data Types in C .................................................................. 27


av
eb

on
Chapter Objectives ........................................................................................................ 29
ee
ns

Simple C Data Types ..................................................................................................... 31


old

Integral Data Types ........................................................................................................ 33


thi

Floating Point Types ...................................................................................................... 35


sw

Derived Data Types ....................................................................................................... 37


ork
bo

Array Data Types - Single and Multi-dimensional ........................................................... 39


ok

Co
Structure Data Types...................................................................................................... 41
,p
lea

Simple Pointer Types ..................................................................................................... 43


se

Pointers to Structures / Multiple Pointers ........................................................................ 45


ca

Pointers to Functions ..................................................................................................... 47


ll 8
00

The const Qualifier ......................................................................................................... 49


-29

Bit Operators ................................................................................................................. 51


py
2-2

Using typedef................................................................................................................. 53
65
2f

Exercises ...................................................................................................................... 55
or

Appendix ....................................................................................................................... 57
a
rew
ard

Chapter 4 - Functions: Calling, Passing, and Returning Values ............................................ 59


.

Chapter Objectives ........................................................................................................ 61


Anatomy of a Function ................................................................................................... 63
Parameter Passing - Pass by Value............................................................................... 65

© 1994-1999 by it courseware, Inc. 8/99


4 Advanced C Programming

Parameter Passing - Pass by Reference ....................................................................... 67


Exercises ...................................................................................................................... 69

Chapter 5 - Standard I/O...................................................................................................... 71


Ev
Chapter Objectives ........................................................................................................ 73
If y

Standard I/O Streams ..................................................................................................... 75


ou

File Access.................................................................................................................... 77
are

Formatted I/O................................................................................................................. 79
be
ing

alu
String I/O ........................................................................................................................ 81
tau

File Positioning Operations............................................................................................ 83


gh

Block I/O ........................................................................................................................ 85


out

Exercises ...................................................................................................................... 87
to
f th
is w

Chapter 6 - Low Level File I/O ............................................................................................. 93


ork

ati
bo

Chapter Objectives ........................................................................................................ 95


ok

Standard I/O vs System I/O............................................................................................. 97


,o
rh

File Access.................................................................................................................... 99
av
eb

Low Level I/O - Read and Write .................................................................................... 101


on
ee

File Positioning............................................................................................................ 103


ns

Error Handling ............................................................................................................. 105


old

Exercises .................................................................................................................... 107


thi
sw
ork

Chapter 7 - Memory Allocation with malloc and calloc ........................................................ 109


bo
ok

Co
,p

Chapter Objectives .......................................................................................................111


lea

Dynamic Memory Allocation Overview.......................................................................... 113


se

malloc(), calloc()........................................................................................................... 115


ca
ll 8

realloc(), free() ............................................................................................................. 117


00

Example ...................................................................................................................... 119


-29

Example: Array of Pointers to Structures ...................................................................... 121


py
2-2
65

Exercises .................................................................................................................... 123


2f
or
a

Chapter 8 - Memory Organization and Scope of Variables ................................................ 125


rew
ard

Chapter Objectives ...................................................................................................... 127


.

Command Line Arguments (argc, argv) ........................................................................ 129


The Memory Layout of a C Program............................................................................. 131
The Stack Segment ..................................................................................................... 133
The Heap Segment ...................................................................................................... 135
Exercises .................................................................................................................... 137

© 1994-1999 by it courseware, Inc. 8/99


Advanced C Programming 5

Chapter 9 - Data Structures: Linked Lists .......................................................................... 139


Chapter Objectives ...................................................................................................... 141
Problem - Array Limitations .......................................................................................... 143
Solution - Linked Lists.................................................................................................. 145
Ev
Linked List - Formation ................................................................................................ 147
List Operations - Delete ............................................................................................... 149
If y

Exercises .................................................................................................................... 151


ou
are
be

Appendix A ....................................................................................................................... 153


ing
tau

alu
Debugging Techniques ................................................................................................ 155
gh

Debugging Hints .......................................................................................................... 157


out

Debugging with Pre-Processing Directives .................................................................. 163


to
f th

Debug Macro............................................................................................................... 165


is w

Symbolic Debuggers ................................................................................................... 167


ork

ati
bo
ok

Appendix B ....................................................................................................................... 169


,o
rh

Coding from Pseudo Code .......................................................................................... 171


av
eb

Project Header Files .................................................................................................... 173


on
ee

Project Source Files .................................................................................................... 175


ns
old

Project Tracking (Bookkeeping) ................................................................................... 177


thi
sw

Appendix C ....................................................................................................................... 179


ork
bo

Overview of the Make Utility ......................................................................................... 181


ok

Co
,p

Using the Make Utility .................................................................................................. 183


lea

Simple Makefile Commands ........................................................................................ 185


se
ca
ll 8

Appendix D ....................................................................................................................... 187


00
-29

Preparing to Use a Debugger ...................................................................................... 189


py
2-2

Project Header Files .................................................................................................... 191


65
2f

Project Source Files .................................................................................................... 193


or

Project Tracking (Bookkeeping) ................................................................................... 195


a
rew
ard

Solutions - Advanced C Programming ............................................................................... 197


.

Exercise Solutions ....................................................................................................... 198

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

old
ns
ee
eb
av
rh

© 1994-1999 by it courseware, Inc. 8/99


Ev
,o
ok
bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
6
Chapter 3 Basic and Derived Data Types in C 27

Chapter 3 - Basic and Derived Data Types in C


Ev
If y
ou
are
be
ing
tau
gh
out
to
alu
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
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
28
Chapter 3 Basic and Derived Data Types in C 29

Chapter Objectives

Use enumerated types to clarify code.

Create and manipulate single and multi-dimensional arrays.


If y

Ev
Create structure types and variables.
ou
are
be

Initialize and manipulate an array of structures.


ing
tau
gh

alu
Declare and use pointers to simple data types.
out
to
f th

Declare and use single and multiple indirection.


is w
ork

ati
Use operators to mask bits.
bo
ok
,o
rh

Protect referenced arguments with const.


av
eb

on
ee

Enhance code readability with typedef statements.


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
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
30
Chapter 3 Basic and Derived Data Types in C 31

Simple C Data Types

All objects must be declared before use.


Ev
Declarations take the form:
type var_identifier [= initializer];
If y
ou
are

Declarations tell the compiler how much room to allocate in memory


be
ing

alu
for the object.
tau
gh

They also define the set of legal values and operations that may
out

be performed on those values.


to
f th

There are two basic C data types:


is w
ork

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

A third type, void, represents an empty set of values.


or
a

It is the return type of functions with no returned value.


rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


32 Advanced C Programming

Notes

Enumerated values make code more readable, and therefore more maintainable.

An an example:
Ev
main()
{
If y

enum apple_types { JONATHAN, MACINTOSH, GRANNY };


ou

enum apple_types apple;


are
be

enum orange_types { VALENCIA, TANGERINE, NAVEL };


ing

alu
enum orange_types orange;
tau
gh
t

for (orange = 0; orange <= 3; orange++)


ou

switch (orange)
to
f th

{
is w

case VALENCIA:
ork

ati
printf ("Just right.\n");
bo

break;
ok
,o

case TANGERINE:
rh

printf ("Too sour.\n");


av

break;
eb

on
ee

case NAVEL:
ns

printf ("Too pulpy.\n");


old

break;
thi

default:
sw

printf ("Is it seedless anyway?\n");


ork

break;
bo
ok

Co

}
,p

/* Though this statement is legal, you should be able to immediately


lea
se

catch this logic mistake. */


ca

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.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 33

Integral Data Types

Integral types are countable finite values.


If y
ou

Ev
The following are integral type object declarations:

char cvar = 'A'; /* 1 byte */


are

int ivar = 5000; /* typically 4 bytes */


be
ing

alu
short sivar = -10; /* typically 2 bytes */
tau

long livar = 1000000 /* typically 4 bytes */


gh
out
to

Character constants are 1 byte integers. They represent the


f th
is w

numeric value of the character in the machine’s character set


ork

ati
(e.g.: ASCII).
bo
ok
,o
rh

Enumerated types are a set of named constants.


av
eb

on
ee
ns

Each value in the set is positionally assigned an incremented


old

integer value, starting with 0.


thi
sw
ork

enum boolean { FALSE, TRUE };


bo
ok

Co
,p
lea

associates FALSE with 0, and TRUE with 1.


se
ca
ll 8

The default assigned integers may be changed:


00
-29

py
2-2

enum colors { RED, YELLOW = 42, GREEN };


65
2f
or

associates RED with 0, YELLOW with 42, and GREEN with 43.
a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


34 Advanced C Programming

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

void main (void)


ou

{
are

double pi = 3.14159;
be
ing
tau

alu
/* attempt to print 16 significant digits */
gh

printf ("The value of pi is %.16f?\n", pi);


out

}
to
f th
is w

produces the result:


ork

ati
bo

The value of pi is 3.1415899999999999?


ok
,o
rh

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
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 35

Floating Point Types

Floating point numbers are real numbers.

They are not exact numbers.


If y

Ev
The following are floating point type object declarations:
ou
are
be

float fvar = 1.24 /* typically 4 bytes */


ing

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
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
36
Chapter 3 Basic and Derived Data Types in C 37

Derived Data Types

Users may declare other types based on the two fundamental C


types. Ev
User defined types are referred to as derived types.
If y
ou

There is an infinite number of derived types.


are
be
ing

alu
Arrays, structures, and pointers are some of the more common
tau
gh

derived types.
out
to
f th

Derived types are constructed to meet a user’s specific needs.


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
.

© 1994-1999 by it courseware, Inc. 8/99


38 Advanced C Programming

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.

To declare the 2-dimensional array num_array, use the following syntax:


Ev
int num_array [2][3];
If y
ou
are

N-dimensional arrays may be initialized by specifying a value for each element. The following may
be

be used to declare and initialize num_array:


ing
tau

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

each with 3 columns. With this in mind, an equivalent initializer is:


ork

ati
bo

int num_array[2][3] = { { 0, 1, 2}, {4, 5, 6}};


ok
,o

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

dimensions. The above definition may be re-written as:


old
thi

int num_array[][3] = { { 0, 1, 2}, {4, 5, 6}};


sw
ork

If there aren’t as many initializing values as are elements in the array, the remaining elements are
bo

automatically initialized to zero. The following are equivalent definitions:


ok

Co
,p
lea

int complex_array[][3][4] = {50,1,2,3,


se

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

int complex_array[][3][4] = {{{50,1,2,3},


ard

{54},
.

{55,56,57,58}},

{{60,1,2,3},
{64,5,6},
{68,9}}};

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 39

Array Data Types - Single and Multi-dimensional

An array is a collection of like-type (homogenous) objects. They may


contain any objects, but all objects in an array must be of the same
type.
If y
ou

Ev
Simple array type objects are declared as:
are
be
ing

alu
type var_identifier [dim] [= {initializers}];
tau
gh
t

dim is the max number of elements in the array.


ou
to
f th
is w

Examples of array object declarations are:


ork

ati
bo
ok
,o

A collection of 81 characters: char string [81];


rh
av

A collection of 5 integers: int int_array [5] = {0, 1, 2, 3, 4};


eb

on
ee
ns
old

Arrays occupy consecutive space in memory.


thi
sw
ork

All arrays in C are indexed from 0 to n-1.


bo
ok

Co
,p
lea

The third element of int_array is accessed by:


se

int_array [2] = 42;


ca
ll 8
00
-29

The array name itself is a constant pointer to the base element of the
py
2-2

array, i.e., int_array == &int_array [0];


65
2f
or
a
rew

More on pointers later.


ard
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
40
Chapter 3 Basic and Derived Data Types in C 41

Structure Data Types

Unlike arrays, a structure type is a collection of differently typed


(heterogenous) objects.
Ev
Structures may contain any other types, including other
If y

structures.
ou
are
be

Structure types are declared as:


ing

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

char name [45];


on
ee
ns

int age;
old

char dept [5];


thi
sw

} exempt;
ork

struct personnel employee;


bo
ok

struct personnel temps [3];


Co
,p

personnel is the (optional) name of the structure type.


lea
se

employee and exempt are objects of the personnel


ca
ll 8

structure type.
00

temps is an array of 3 personnel structure objects.


-29

py
2-2
65

You may initialize a structure object:


2f
or

struct personnel supervisor = {"Fred", 42, "PRES"};


a
rew
ard

Access the individual fields of a structure using the ‘dot-notation’:


.

exempt.age = 45;
strcpy (exempt.name, "Fredina");
temps [0].age = 45;

© 1994-1999 by it courseware, Inc. 8/99


42 Advanced C Programming

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

int iaray [3];


are

int *pi = iaray; /* Why is this ok? */


be
ing

alu
for (i = 0; i<3; i++)
tau

*pi++ = i;
gh
out

will assign the values:


to
f th
is w

iaray [0] = 0, iaray [1] = 1, iaray [2] = 2.


ork

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
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 43

Simple Pointer Types

Pointer variables point to another variable or function.

A pointer variable contains the address of an object.


If y

Ev
- The address of an object is obtained with the & operator.
ou
are
be

The object pointed to contains a value of the referenced type.


ing
tau
gh

alu
Objects are indirectly referenced through pointers.
out
to
f th

Pointer type objects are declared as:


is w
ork

ati
type * pvar [= initializer];
bo
ok
,o
rh

Two ways of assigning to pointers are:


av
eb

on
ee

Statically assigning the address of an already existing object of


ns
old

the appropriate type.


thi
sw
ork

Dynamically allocating space, and assigning the base address


bo

to the pointer variable. (We will cover this shortly.)


ok

Co
,p
lea

Examples of pointer object declarations and static assignments are:


se
ca
ll 8
00

float fvar = 52.31;


-29

int ivar = 42;


py
2-2

int * pivar = &ivar;


65
2f

float * pfvar = &fvar;


or
a

/* pfvar = &ivar; Warning : mismatched types */


rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


44 Advanced C Programming

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

struct student_info **ptr_ptr_student = &ptr_student;


ou
are

ptr_ptr_student is a pointer to a pointer to student_info structure. You may think


be
ing

of this as looking like:


tau
gh

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

Fields of the student_info structure may be accessed with the syntax:


ork
bo
ok

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

may also be written as:


65
2f
or

ptr_ptr_student [0] ->address


a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 45

Pointers to Structures / Multiple Pointers

A structure pointer is declared as:


If y
ou

Ev
struct name *pstr [= initializer];

pstr_stu below is an example of a structure pointer, initialized to


are

the address of graduate:


be
ing
tau

alu
struct student_info {
gh
t

char name [30];


ou
to

long ssn;
f th
is w

float gpa;
ork

ati
char address [50];
bo

} senior, graduate;
ok
,o
rh
av

struct student_info *pstr_stu = &graduate;


eb

on
ee
ns

Fields within the structure may be indirectly referenced:


old
thi

The ()’s are necessary. Why?


sw
ork

(*pstr_stu).gpa = senior.gpa;
bo
ok

Co
,p

Equivalently, the above may use the more common shorthand


lea
se

notation:
ca

pstr_stu->gpa = senior.gpa;
ll 8
00
-29

py
2-2

Arrays of pointers to structures are often used:


65
2f

struct student_info *pstr_stu_aray [3];


or
a
rew

Values may be assigned using the below notation:


ard
.

pstr_stu_aray [0] = pstr_stu;


pstr_stu_aray [0]->gpa = pstr_stu->gpa;

© 1994-1999 by it courseware, Inc. 8/99


46 Advanced C Programming

Notes

Why use function pointers? Two main reasons are:

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

a function pointer in them.


ou
are

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

(see chapter appendix for an example).


is w
ork

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

void print_name (void);


old

void print_age (void);


thi
sw

void (*func_select[2]) (void) = {print_name, print_age};


ork
bo

/* Invoke all functions by looping, instead of individual calls */


ok

Co

for (i=0; i<2; i++)


,p

func_select [i] ();


lea
se

}
ca

void print_name (void)


ll 8

{
00
-29

printf ("Hi, my name is Denise.\n");


py
2-2

}
65

void print_age (void)


2f

{
or
a

printf ("Huh, I’m still 29 and holding.\n");


rew

}
ard
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 47

Pointers to Functions

You may also create pointers to functions.


Similar to arrays, function names are themselves pointers:
Ev
int (*myfunc) ();
If y
ou
are

declares myfunc to be a pointer to a function (myfunc) that returns


be
ing

alu
an int.
tau

Also like arrays, function names are constant pointers and can
gh
out

not be reassigned.
to
f th

To create a variable function pointer, use the following syntax:


is w

int (* ptr_func) ();


ork

ati
bo

ptr_func = myfunc;
ok
,o

declares ptr_func as a (variable) pointer to a function


rh
av

returning an int. ptr_func is then assigned the address of


eb

function myfunc.
on
ee
ns

Here is a brief example of how to use function pointers:


old
thi

main()
sw

{
ork

int fn0 (void), fn1 (void);


bo
ok

int (*func_select[2]) (void) = {fn0, fn1};


Co
,p

int result;
lea
se
ca

result = func_select[0]();
ll 8

printf (“result 1 is %d\n”,result);


00
-29

result = func_select[1]();
py
2-2

printf (“result 2 is %d\n”,result);


65

}
2f
or

int fn0 (void)


a
rew

{
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

void b(const int *a);


be
ing

alu
main()
tau

{
gh

int a = 42;
out

printf ("BEFORE b: The value of a is %d.\n",a);


to
f th

b(&a);
is w

printf ("AFTER b: The value of a is %d.\n",a);


ork

ati
}
bo

void b(const int *a)


ok
,o

{
rh

(*a)++; /* ERROR */
av
eb

}
on
ee
ns
old

produces the following error on compilation:


thi
sw

"err.c", line 9: operand must be modifiable lvalue: op "++"


ork
bo
ok

Co
,p
lea
se
ca
ll 8
00
-29

py
2-2
65
2f
or
a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 49

The const Qualifier

const is used as a qualifier to specify that a value is not to be


modified. Ev
const binds to the type of the value.
If y
ou

Examples:
are
be
ing

alu
void *strcpy (char *target, const char *source);
tau
gh

or equivalently
out

void *strcpy (char *target, char const *source);


to
f th
is w

source is a pointer to a constant character. The pointer may


ork

ati
bo

be updated, but the value pointed to remains unchanged.


ok
,o
rh

void get_loan (const float *const fixed_rate);


av
eb

on
ee
ns

fixed_rate is a constant pointer to a constant float. Neither


old

the pointer nor the float values may be altered.


thi
sw
ork

Constant objects must be initialized.


bo
ok

Co
,p
lea

const int a = 42;


se

const int b; /* b is not automatically initialized */


ca

b = a; /* illegal: b is a constant and cannot be assigned */


ll 8
00
-29

py
2-2
65
2f
or
a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


50 Advanced C Programming

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

employee’s information could be stored within one (unsigned) short integer:


are
be

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

/* unpack the data for display */


ork

ati
void unmask (unsigned short emp,
bo

unsigned int *id,


ok
,o

unsigned int *yrs,


rh

unsigned int *dept_no);


av
eb

on
unsigned int id, dept_no, yrs;
ee
ns

unsigned short employee = 0;


old
thi

printf ("Enter the employee’s id yrs deptno ");


sw

scanf ("%d %d %d", &id, &yrs, &dept_no);


ork

fflush (stdin);
bo
ok

Co

/* pack the data, shifting to store each new piece */


,p

employee |= id;
lea

employee = (employee << 5) | yrs;


se
ca

employee = (employee << 5) | dept_no;


ll 8
00

/* unpack the data for display */


-29

unmask (employee, &id, &yrs, &dept_no);


py
2-2

printf ("%d %d %d\n", id, yrs, dept_no);


65

}
2f

void unmask (unsigned short emp,


or
a

unsigned int *id,


rew

unsigned int *yrs,


ard

unsigned int *dept_no)


.

{
/* 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

The bitwise operators are:

~ (complement) | (or)
Ev
& (and) << (left shift)
If y

^ (XOR) >> (right shift)


ou
are
be

Bit operators take integral arguments.


ing

alu
The arguments are treated as strings of zeroes and ones.
tau
gh

Examples:
out
to
f th

2 00000000 00000000 00000000 00000010


is w

& 3 & 00000000 00000000 00000000 00000011


ork

ati
2 00000000 00000000 00000000 00000010
bo
ok
,o
rh

2 << 3 00000000 00000000 00000000 00000010


av
eb

16 00000000 00000000 00000000 00010000


on
ee
ns
old

21 >> 2 00000000 00000000 00000000 00010101


thi

5 00000000 00000000 00000000 00000101


sw
ork
bo

You can use the bit operators to extract bits from a variable.
ok

Co
,p

The constant used to extract the bits is called a mask.


lea

For example, to verify that a number is odd, you need only status the
se
ca

least significant bit (and the variable with a mask of 1):


ll 8
00
-29

3 00000000 00000000 00000000 00000011


py
2-2
65

&1 00000000 00000000 00000000 00000001 (mask)


2f
or

1 00000000 00000000 00000000 00000001 (true)


a
rew
ard
.

22 00000000 00000000 00000000 00010110


&1 00000000 00000000 00000000 00000001 (mask)
0 00000000 00000000 00000000 00000000 (false)

© 1994-1999 by it courseware, Inc. 8/99


52 Advanced C Programming

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

avoided with the use of typedef:


be
ing
tau

alu
typedef struct {
gh

string fname;
out

string lname;
to
f th

FEET height;
is w

}student;
ork

ati
bo

student junior, senior, graduate;


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
.

© 1994-1999 by it courseware, Inc. 8/99


Chapter 3 Basic and Derived Data Types in C 53

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

typedef char * string;


is w

string firstname, lastname;


ork

ati
bo
ok

creates an additional name for the type char * and creates two
,o
rh

string objects.
av
eb

on
ee

typedef int vector [5];


ns
old

vector array;
thi

...
sw
ork

array[0] = 42;
bo
ok

Co
,p

Use the typedef facility to enhance code readability.


lea
se
ca
ll 8
00
-29

py
2-2
65
2f
or
a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
54
Chapter 3 Basic and Derived Data Types in C 55

Exercises

1) Create a program that displays a 4 option menu. The options to be included


are: Ev
e - Enter a new employee’s information
a - Display all employees information
If y

d - Display an employee’s information (optional)


ou
are

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

Store the information as an array of structures.


is w
ork

ati
3) Option a:
bo
ok

Display information entered for all employees.


,o
rh
av

4) Option q:
eb

Quit the program.


on
ee
ns
old

Optional
thi
sw
ork

A) Option d:
bo

If option d is selected, prompt the user for the employee’s name.


ok

Co
,p

Search the array. If found, display the employee. If not found, allow the user
lea

to enter the new employee if they choose.


se
ca
ll 8
00
-29

py
2-2
65
2f
or
a
rew
ard
.

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
56
Chapter 3 Basic and Derived Data Types in C 57

Appendix
#include <stdio.h>
#include <stdlib.h>

typedef struct emps {


char name [20];
int age;
} employee;
Ev
void swap (employee v[], int (*compare)(employee v[]));
If y
ou

void main (void)


are

{
int i;
be
ing

int name_compare (employee v[]); /* determines greater name */


alu
int age_compare (employee v[]); /* determines greater age */
tau

int (*compare)(employee v[]);


gh

employee emp[2];
out

strcpy (emp[0].name, "phido"); emp[0].age = 7;


to

strcpy (emp[1].name, "fred"); emp[1].age = 12;


f th
is w

/* do swap based on names first */


ork

ati
compare = name_compare;
bo

puts ("BEFORE NAME SWAP");


ok

printf ("%s %d\n", emp[0].name, emp[0].age);


,o

printf ("%s %d\n", emp[1].name, emp[1].age);


rh

swap (emp, compare);


av

puts ("AFTER NAME SWAP");


eb

printf ("%s %d\n", emp[0].name, emp[0].age);


on
ee

printf ("%s %d\n", emp[1].name, emp[1].age);


ns
old

/* do swap based on age */


compare = age_compare;
thi

puts ("BEFORE AGE SWAP");


sw

printf ("%s %d\n", emp[0].name, emp[0].age);


ork

printf ("%s %d\n", emp[1].name, emp[1].age);


bo

swap (emp, compare);


ok

puts ("AFTER AGE SWAP");


Co
,p

printf ("%s %d\n", emp[0].name, emp[0].age);


printf ("%s %d\n", emp[1].name, emp[1].age);
lea

}
se

int name_compare (employee v[])


ca

{
ll 8

return (strcmp (v[0].name, v[1].name));


00

} /* name_compare */
-29

int age_compare (employee v[])


py
2-2

{
65

return (v[0].age - v[1].age);


2f

} /* age_compare */
or

void swap (employee v[], int (*compare)(employee v[]))


a

{
rew

employee temp;
/* compare function called depends on which was sent in */
ard

if (compare (v) > 0)


.

{
temp = v[0];
v[0] = v[1];
v[1] = temp;
}
} /* swap */

© 1994-1999 by it courseware, Inc. 8/99


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
Advanced C Programming

ee
eb
av
rh
Ev
,o
ok

© 1994-1999 by it courseware, Inc. 8/99


bo
ork
is w
f th
to
t ou
gh
tau
ing
be
are
ou
If y
Notes
58

Vous aimerez peut-être aussi