08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10 ■ Structures

while (k > 0 && strcmp(insertItem.name, person[k].name) < 0) {

person[k + 1] = person[k];

--k;

}

person[k + 1] = insertItem;

}

} //end sortByName

The function sortByName is identical with sortByVote except for the while condition, which

specifies which field is used in comparisons and the use of < for sorting in ascending order. Note

the use of the standard string function, strcmp, for comparing two names. If strcmp(s1, s2) is

negative, it means that the string s1 comes before the string s2 in alphabetical order.

As an exercise, rewrite the program for solving the voting problem so that it prints the results

in descending order by votes and in alphabetical order.

10.10 Pass Structures to Functions

In the voting problem, we saw examples where candidate, an array of structures, was passed

to various functions. We now discuss some other issues that arise in passing a structure to a

function.

Consider a structure for a “book type” with the following fields:

typedef struct {

char author[31];

char title[51];

char binding; //paperback, hardcover, spiral, etc.

double price;

int quantity; //quantity in stock

} Book;

Book text;

This declares a new type called Book, and text is declared as a variable of type Book.

We could pass individual fields to functions in the usual way; for a simple variable, its value is

passed, but, for an array variable, its address is passed. Thus:

fun1(text.quantity); // value of text.quantity is passed

fun2(text.binding); // value of text.binding is passed

fun3(text.price); // value of text.price is passed

but,

fun4(text.title); // address of array text.title is passed

We could even pass the first letter of the title, as follows:

fun5(text.title[0]); // value of first letter of title is passed

304

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!