Sams Teach Yourself C in 24 Hours (35 page)

BOOK: Sams Teach Yourself C in 24 Hours
9.26Mb size Format: txt, pdf, ePub

18:

19: return 0;

20: }

When I run executable 12L04.exe, the following output is displayed:

array_ch[0] contains: H

OUTPUT
array_ch[1] contains: e

array_ch[2] contains: l

array_ch[3] contains: l

array_ch[4] contains: o

array_ch[5] contains: !

array_ch[6] contains:

Put all elements together(Method I):

Hello!

Put all elements together(Method II):

Hello!

As you can see from Listing 12.4, a character array, array_ch, is declared and
ANALYSIS
initialized in line 6. Each element in the character array is printed out by the printf() call in a for loop shown in lines 9 and 10. There is a total of seven elements in the array; they contain the following character constants: ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’, and ‘\0’.

There are two ways to display this array: display all the characters individually, or treat them as a character string.

12

Lines 12–14 show the first way, which fetches each individual element, array_ch[i], consecutively in a loop, and prints out one character next to another by using the character format specifier %c in the printf() call in line 14.

Whenever you are dealing with a character array, as was mentioned earlier, the null character ‘\0’ signals the end of the string (even though it may not yet be the end of the array). It is a good idea to watch for the null character so you know when to stop printing, so the conditional expression in line 13 will terminate the for loop if the current element is a null character.

The second way is simpler. You simply tell the printf() function where to find the first element the array (the address of its first element). Also, you need to use the string format specifier %s in the printf() call as shown in line 17. Note that the array_ch expression in line 17 contains the address of the first element in the array—that is, the starting address of the array. The name of the array, by itself, is a shorthand way of saying array_ch[0]; they mean the same thing.

16 067231861x CH12 1/25/00 10:18 AM Page 198

198

Hour 12

You may be wondering how the printf() function knows where the end of the character array is. Do you remember that the last element in the character array array_ch is a ‘\0’

character? It’s this null character that marks the end of the string. As I mentioned earlier, a contiguous sequence of characters ending with a null character is called a character string in C. We don’t tell printf() how many elements are in the array, so the %s format specifier tells printf() to keep printing characters until it finds a null character—just as we did, ourselves, in the first method.

The Null Character (
‘\0’
)

The null character (‘\0’) is treated as one character in C; it is a special character that marks the end of a string. Therefore, when functions like printf() act on a character string, they process one character after another until they encounter the null character.

(You’ll learn more about strings in Hour 13.)

The null character (‘\0’), which is always evaluated as a value of zero, can also be used for a logical test in a control-flow statement. Listing 12.5 shows an example of using the null character in a for loop.

TYPE

LISTING 12.5

Ending Output at the Null Character

1: /* 12L05.c: Stopping at the null character */

2: #include

3:

4: main()

5: {

6: char array_ch[15] = {‘C’, ‘ ‘,

7: ‘i’, ‘s’, ‘ ‘,

8: ‘p’, ‘o’, ‘w’, ‘e’, ‘r’,

9: ‘f’, ‘u’, ‘l’, ‘!’, ‘\0’};

10: int i;

11: /* array_ch[i] in logical test */

12: for (i=0; array_ch[i]; i++)

13: printf(“%c”, array_ch[i]);

14:

15: printf(“\n”);

16: return 0;

17: }

By running the executable 12L05.exe, I obtain the following output:

C is powerful!

OUTPUT

16 067231861x CH12 1/25/00 10:18 AM Page 199

Understanding Arrays

199

In Listing 12.5, a character array, array_ch, is declared and initialized, with the
ANALYSIS
characters (including the space characters) from the string C is powerful!, in lines 6–9.

Note that the last element in the array contains the null character (‘\0’), which is needed to terminate the string.

The for loop in lines 12 and 13 prints out each element in the array array_ch to show the string C is powerful! on the screen. So in the first expression of the for statement, the integer variable i, which is used as the index to the array, is initialized to 0.

Then, the conditional expression, array_ch[i], is evaluated. If the expression evaluates to a nonzero value, the for loop iterates; otherwise, the loop stops. Starting at the first element in the array, the array_ch[i] expression keeps producing a nonzero value until the null character is encountered. Therefore, the for loop can put all characters of the array on the screen, and stop printing right after the array_ch[i] expression produces a value of zero, when it finds the null character

Multidimensional Arrays

So far, all the arrays you’ve seen have been one-dimensional arrays, in which the dimension sizes are placed within a pair of brackets ([ and ]).

In addition to one-dimensional arrays, the C language also supports multidimensional arrays. You can declare arrays with as many dimensions as your compiler allows.

The general form of declaring a
N
-dimensional array is

12

data-type

Array-Name[Array-Size1][Array-Size2]. . . [Array-SizeN];

where N can be any positive integer.

Because the two-dimensional array, which is widely used, is the simplest form of the multidimensional array, let’s focus on two-dimensional arrays in this section. Anything you learn from this section can be applied to arrays of more than two dimensions, however.

For example, the following statement declares a two-dimensional integer array: int array_int[2][3];

Here there are two pairs of brackets that represent two dimensions with a size of 2 and 3

integer elements, respectively.

You can initialize the two-dimensional array array_int in the following way: array_int[0][0] = 1;

array_int[0][1] = 2;

16 067231861x CH12 1/25/00 10:18 AM Page 200

200

Hour 12

array_int[0][2] = 3;

array_int[1][0] = 4;

array_int[1][1] = 5;

array_int[1][2] = 6;

which is equivalent to the statement

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

Also, you can initialize the array_int array in the following way:

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

Note that array_int[0][0] is the first element in the two-dimensional array array_int; array_int[0][1] is the second element in the array; array_int[0][2] is the third element; array_int[1][0] is the fourth element; array_int[1][1] is the fifth element; and array_int[1][2] is the sixth element in the array.

The program in Listing 12.6 shows a two-dimensional integer array that is initialized and displayed on the screen.

TYPE

LISTING 12.6

Printing a Two-Dimensional Array

1: /* 12L06.c: Printing out a 2-D array */

2: #include

3:

4: main()

5: {

6: int two_dim[3][5] = {1, 2, 3, 4, 5,

7: 10, 20, 30, 40, 50,

8: 100, 200, 300, 400, 500};

9: int i, j;

10:

11: for (i=0; i<3; i++){

12: printf(“\n”);

13: for (j=0; j<5; j++)

14: printf(“%6d”, two_dim[i][j]);

15: }

16: printf(“\n”);

17: return 0;

18: }

The following output is obtained by running the executable 12L06.exe:

1 2 3 4 5

OUTPUT

10 20 30 40 50

100 200 300 400 500

16 067231861x CH12 1/25/00 10:18 AM Page 201

Understanding Arrays

201

As you can see in Listing 12.6, there is a two-dimensional integer array, two_dim,
ANALYSIS
declared and initialized in lines 6–8.

In lines 11–15, two for loops are nested together. The outer for loop increments the integer variable i and prints out the newline character ‘\n’ in each iteration. Here the integer variable i is used as the index to the first dimension of the array, two_dim.

The inner for loop in lines 13 and 14 prints out each element, represented by the expression two_dim[i][j], by incrementing the index to the second dimension of the array.

Therefore, I obtain the following output:

1 2 3 4 5

10 20 30 40 50

100 200 300 400 500

after the two nested for loops are run successfully.

Unsized Arrays

As you’ve seen, the size of a dimension is normally given during the declaration of an array. It means that you have to count each element in an array to determine the size. It could be tedious to do so, though, especially if there are many elements in an array.

The good news is that the C compiler can actually calculate a dimension size of an array automatically if an array is declared as an
unsized array
. For example, when the compiler sees the following unsized array:

int list_int[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90};

12

it will create an array big enough to store all the elements.

Likewise, you can declare a multidimensional unsized array. However, you have to specify all but the leftmost (that is, the first) dimension size. For instance, the compiler can reserve enough memory space to hold all elements in the following two-dimensional unsized array:

char list_ch[][2] = {

‘a’, ‘A’,

‘b’, ‘B’,

‘c’, ‘C’,

‘d’, ‘D’,

‘e’, ‘E’,

‘f’, ‘F’,

‘g’, ‘G’};

The program in Listing 12.7 initializes a one-dimensional character unsized array and a two-dimensional unsized integer array, and then measures the memory spaces taken for storing the two arrays.

16 067231861x CH12 1/25/00 10:18 AM Page 202

202

Hour 12

TYPE

LISTING 12.7

Initializing Unsized Arrays

1: /* 12L07.c: Initializing unsized arrays */

2: #include

3:

4: main()

5: {

6: char array_ch[] = {‘C’, ‘ ‘,

7: ‘i’, ‘s’, ‘ ‘,

8: ‘p’, ‘o’, ‘w’, ‘e’, ‘r’,

9: ‘f’, ‘u’, ‘l’, ‘!’, ‘\0’};

10: int list_int[][3] = {

11: 1, 1, 1,

12: 2, 2, 8,

13: 3, 9, 27,

14: 4, 16, 64,

15: 5, 25, 125,

16: 6, 36, 216,

17: 7, 49, 343};

18:

19: printf(“The size of array_ch[] is %d bytes.\n”, sizeof (array_ch)); 20: printf(“The size of list_int[][3] is %d bytes.\n”, sizeof (list_int)); 21: return 0;

22: }

The following output is obtained when the executable 12L07.exe is run on my computer: The size of array_ch[] is 15 bytes.

OUTPUT
The size of list_int[][3] is 42 bytes.

A character unsized array, array_ch, is declared and initialized in lines 6–9. In
ANALYSIS
lines 10–17, a two-dimensional unsized integer array, list_int, is declared and initialized too.

The statement in line 19 measures and prints out the total memory space (in bytes) taken by the array array_ch. The result shows that the unsized character array is assigned 15

bytes in memory to hold all its elements after compiling. When you calculate the total number of the elements in the character array manually, you find that there are indeed 15

elements. Because each character takes one byte in the memory, the character array array_ch takes total of 15 bytes accordingly.

Likewise, the statement in line 20 gives the total number of bytes reserved in the memory for the unsized two-dimensional integer array list_int. Because there are a total of 21 integer elements in the array, and an integer takes 2 bytes on my machine, the compiler should allocate 42 bytes for the integer array list_int. The result printed out by the printf() function in line 20 proves that there are 42 bytes reserved in the memory 16 067231861x CH12 1/25/00 10:18 AM Page 203

Understanding Arrays

203

for the two-dimensional integer array. (If the size of int is different on your machine, you may get different values for the size of the list_int array in program Listing 12.7.)
Summary

In this lesson you learned the following very important concepts about arrays in C:

• An array is a collection of variables that are of the same data type.

• In C, the index to an array starts at 0.

• You can initialize each individual element of an array after the declaration of the array, or you can place all initial values into a data block surrounded by { and }

during the declaration of an array.

• The memory storage taken by an array is determined by multiplying the size of the data type and the dimensions of the array.

• A pointer is said to
refer to
an array when the address of the first element in the array is assigned to the pointer. The address of the first element in an array is also called the start address of the array.

• To assign the start address of an array to a pointer, you can put either the combination of the address-of operator (&) and the first element name of the array, or simply use the array name on the right side of an assignment operator (=).

• The null character (‘\0’) marks the end of a string. C functions, such as printf(), will stop processing the string when the null character is encountered.

Other books

Dragon Master by Alan Carr
Once Upon a Highland Autumn by Lecia Cornwall
Forever & an Engine by C. J. Fallowfield
The Dead Travel Fast by Deanna Raybourn
Up in Smoke by Alice Brown
Bone Island Mambo by Tom Corcoran
Naughty Nicks by d'Abo, Christine
The Absentee by Maria Edgeworth
A Regency Christmas Pact Collection by Ava Stone, Jerrica Knight-Catania, Jane Charles, Catherine Gayle, Julie Johnstone, Aileen Fish