08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 ■ Searching, Sorting, and Merging

9.4 Sort an Array of Strings

Consider the problem of sorting a list of names in alphabetical order. We have seen that, in C,

each name is stored in a character array. To store several names, we need a two-dimensional

character array. For example, consider the following list of names.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

0 S a m l a l , R a w l E \0

1 W i l l i a m s , M a r k \0

2 D e l w i n , M a c \0

3 T a y l o r , V i c t o r \0

4 M o h a m e d , A b u \0

5 S i n g h , K R i s h n a \0

6 T a w a r i , T a u \0

7 A b d o o l , Z a i d \0

To store this list, we will require a declaration such as the following:

char list[8][15];

To cater for longer names, we can increase 15, and to cater for more names, we can increase 8.

The process of sorting list is essentially the same as sorting an array of integers. The major

difference is that whereas we use < to compare two numbers, we must use strcmp to compare two

names. In the function insertionSort shown earlier, the while condition changes from this:

while (k >= lo && key < list[k])

to the following, where key is now declared as char key[15]:

while (k >= lo && strcmp(key, list[k]) < 0)

Also, we must now use strcpy (since we can’t use = for strings) to assign a name to another

location. We will see the complete function in the next section.

9.4.1 Variable-Length Arrays

We will use this example to show how variable-length arrays (VLAs) may be used in C. This

feature is available only in C versions from C99 and later. The idea is that the size of an array may

be specified at runtime as opposed to compile time.

In the function below, note the declaration of list (char list[][max]) in the parameter

list. The size of the first dimension is left unspecified, as for one-dimensional arrays. The size

of the second dimension is specified using the parameter max; the value of max will be specified

when the function is called. This gives us a bit more flexibility since we can specify the size of the

second dimension at runtime.

260

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!