Sams Teach Yourself C in 24 Hours (34 page)

For example, an array of integers is declared in the following statement, int array_int[8];

where int specifies the data type of the array whose name is array_int. The size of the array is 8, which means that the array can store eight elements (that is, integers in this case).

In C, you have to declare an array explicitly, as you do for other variables, before you can use it.

Indexing Arrays

After you declare an array, you can access each of the elements in the array separately.

For instance, the following declaration declares an array of characters: char day[7];

You can access the elements in the array of day one after another. To do this, you use the array name in an expression followed by a number, called an
index
, enclosed in brackets.

The important thing to remember is that all arrays in C are indexed starting at 0. In other words, the index to the first element in an array is 0, not 1. Therefore, the first element in the array of day is day[0]. Because there are 7 elements in the day array, the last element is day[6], not day[7].

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

Understanding Arrays

191

The seven elements of the array have the following expressions: day[0], day[1], day[2], day[3], day[4], day[5], and day[6].

Because these expressions reference the elements in the array, they are sometimes called
array element references
.

Initializing Arrays

With the help of the array element references, you can initialize each element in an array.

For instance, you can initialize the first element in the array of day, which was declared in the last section, like this:

day[0] = ‘S’;

Here the numeric value of S is assigned to the first element of day, day[0].

Likewise, the statement day[1] = ‘M’; assigns ‘M’ to the second element, day[1], in the array.

The second way to initialize an array is to initialize all elements in the array together. For instance, the following statement initializes an integer array, arInteger: int arInteger[5] = {100, 8, 3, 365, 16};

Here the integers inside the braces ({ and }) are correspondingly assigned to the elements of the array arInteger. That is, 100 is given to the first element (arInteger[0]), 8 to the second element (arInteger[1]), 3 to the third (arInteger[2]), and so on.

Listing 12.1 gives another example of initializing arrays.

12

TYPE

LISTING 12.1

Initializing an Array

1: /* 12L01.c: Initializing an array */

2: #include

3:

4: main()

5: {

6: int i;

7: int list_int[10];

8:

9: for (i=0; i<10; i++){

10: list_int[i] = i + 1;

11: printf( “list_int[%d] is initialized with %d.\n”, i, list_int[i]); 12: }

13: return 0;

14: }

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

192

Hour 12

The following output is displayed on the screen after the executable (12L01.exe) of the program in Listing 12.1 is created and run on my computer:

list_int[0] is initialized with 1.

OUTPUT
list_int[1] is initialized with 2.

list_int[2] is initialized with 3.

list_int[3] is initialized with 4.

list_int[4] is initialized with 5.

list_int[5] is initialized with 6.

list_int[6] is initialized with 7.

list_int[7] is initialized with 8.

list_int[8] is initialized with 9.

list_int[9] is initialized with 10.

As you can see in Listing 12.1, there is an integer array, called list_int, which
ANALYSIS
is declared in line 7. The array list_int contains 10 elements.

Lines 9–12 make up a for loop that iterates 10 times. The statement in line 10 initializes list_int[i], the
i
th element of the array list_int, with the result of the expression i + 1.

Line 11 then prints out the name of the element, list_int[i], and the value assigned to the element.

The Size of an Array

As mentioned earlier in this lesson, an array consists of consecutive memory locations.

Given an array, like this:

data-type

Array-Name[Array-Size];

you can then calculate the total bytes of the array by the following expression: sizeof(data-type) * Array-Size

Here data-type is the data type of the array; Array-Size specifies the total number of elements the array can take. This expression evaluates to the total number of bytes the array takes.

Another way to calculate the total bytes of an array is simpler; it uses the following expression:

sizeof(Array-Name)

Here Array-Name is the name of the array.

The program in Listing 12.2 shows how to calculate the memory space taken by an array.

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

Understanding Arrays

193

TYPE

LISTING 12.2

Calculating the Size of an Array

1: /* 12L02.c: Total bytes of an array */

2: #include

3:

4: main()

5: {

6: int total_byte;

7: int list_int[10];

8:

9: total_byte = sizeof (int) * 10;

10: printf( “The size of int is %d-byte long.\n”, sizeof (int));

11: printf( “The array of 10 ints has total %d bytes.\n”, total_byte); 12: printf( “The address of the first element: %p\n”, &list_int[0]); 13: printf( “The address of the last element: %p\n”, &list_int[9]); 14: return 0;

15: }

After running the executable 12L02.exe, I have the following output displayed on the screen of my computer:

The size of int is 2-byte long.

OUTPUT
The array of 10 ints has total 20 bytes

The address of the first element: 0x1806

The address of the last element: 0x1818

Note that you might get different address values when you run the program in
ANALYSIS
Listing 12.2 on your machine. However, the difference between the address of the first element and the address of the last element should equal the total number of
12

bytes in the array.

In Listing 12.2, there is an integer array, list_int, which is declared in line 7. The total memory space taken by the array is the result of multiplying the size of int and the total number of elements in the array. As declared in this example, there are a total of 10 elements in the array list_int.

The statement in line 10 prints out the size of int on my machine. You can see from the output that each integer element in the array takes 2 bytes. Therefore, the total memory space (in bytes) taken by the array is 10 * 2. In other words, the statement in line 9

assigns the value of 20, produced by the expression sizeof (int) * 10, to the integer variable total_byte. Line 11 then displays the value contained by the total_byte variable on the screen.

To prove that the array does take the consecutive memory space of 20 bytes, the address of the first element in the array is printed out by the statement in line 12. Note that the ampersand (&), which was introduced as the address-of operator in Hour 11,

“Understanding Pointers,” is used in line 12 to obtain the address of the first element, 16 067231861x CH12 1/25/00 10:18 AM Page 194

194

Hour 12

list_int[0], in the array. Here the address of the first element is the starting address of the array. From the output, you can see that the address of the list_int[0] element is 0x1806 on my machine.

Then, the &list_int[9] expression in line 13 evaluates to the address of the final element in the array, which is 0x1818 on my machine. Thus, the distance between the last element and the first element is 0x1818–0x1806, or 18 bytes.

As mentioned earlier in the book, hexadecimal is a 16-based numbering system. We know that 0x1818 minus 0x1806 produces 0x0012 (that is, 0x12). Then 0x12 in hexadecimal is equal to 1*16 + 2 that yields 18 in decimal.

Because each element takes 2 bytes, and the address of the final element is the beginning of that 2-byte element, the total number of bytes taken by the array list_int is indeed 20 bytes. You can calculate it another way: The distance between the last element and the first element is 18 bytes. The total number of bytes taken by the array should be counted from the very first byte in the first element to the last byte in the last element. Therefore, the total number bytes taken by the array is equal to 18 plus 2, that is 20 bytes.

Figure 12.1 shows you the memory space taken by the array list_int

FIGURE 12.1

The memory space

taken by the array

&list_int[0]

0x1806

1 byte

2 bytes

list_int
.

}

1 byte

1 byte

2 bytes

}

1 byte

&list_int[9]

0x1818

1 byte

2 bytes

}

1 byte

Arrays and Pointers

As I mentioned earlier in this hour, pointers and arrays have a close relationship in C. In fact, you can make a pointer that refers to the first element of an array by simply assign-16 067231861x CH12 1/25/00 10:18 AM Page 195

Understanding Arrays

195

ing the array name to the pointer variable. If an array is referenced by a pointer, the elements in the array can be accessed with the help of the pointer.

For instance, the following statements declare a pointer and an array, and assign the address of the first element to the pointer variable:

char *ptr_c;

char list_c[10];

ptr_c = list_c;

Because the address of the first element in the array list_c is the beginning address of the array, the pointer variable ptr_c is actually now referencing the array via the beginning address.

Listing 12.3 demonstrates how to reference an array with a pointer.

TYPE

LISTING 12.3

Referencing an Array with a Pointer

1: /* 12L03.c: Referencing an array with a pointer */

2: #include

3:

4: main()

5: {

6: int *ptr_int;

7: int list_int[10];

8: int i;

9:

10: for (i=0; i<10; i++)

11: list_int[i] = i + 1;

12: ptr_int = list_int;

12

13: printf( “The start address of the array: %p\n”, ptr_int);

14: printf( “The value of the first element: %d\n”, *ptr_int);

15: ptr_int = &list_int[0];

16: printf( “The address of the first element: %p\n”, ptr_int);

17: printf( “The value of the first element: %d\n”, *ptr_int);

18: return 0;

19: }

After the executable 12L03.exe is run on my computer, the following output is displayed on the screen:

The start address of the array: 0x1802

OUTPUT
The value of the first element: 1

The address of the first element: 0x1802

The value of the first element: 1

In Listing 12.3, an integer pointer variable, ptr_int, is declared in line 6. Then,
ANALYSIS
an integer array, list_int, which is declared in line 7, is initialized by the list_int[i] = i + 1 expression in a for loop. (See lines 10 and 11.)

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

196

Hour 12

The statement in line 12 assigns the address of the first element in the array to the pointer variable ptr_int. To do so, the name of the array list_int is simply placed on the right side of the assignment operator (=) in line 12.

Line 13 displays the address assigned to the pointer variable ptr_int. The output shows that 0x1802 is the start address of the array. (You might get a different address on your machine.) The *ptr_int expression in line 14 evaluates to the value referenced by the pointer. This value is the same value contained by the first element of the array, which is the initial value, 1, assigned in the for loop. You can see that the output from the statement in line 14 shows the value correctly.

The statement in line 15 is equivalent to the one in line 12, which assigns the address of the first element to the pointer variable. Lines 16 and 17 then print out the address and the value kept by the first element, 0x1802 and 1, respectively.

In Hour 16, “Applying Pointers,” you’ll learn to access an element of an array by incrementing or decrementing a pointer.

Displaying Arrays of Characters

This subsection focuses on arrays of characters. The char data type takes one byte.

Therefore, each element in a character array is one byte long. The total number of elements in a character array is the total number of bytes the array takes in the memory.

More importantly in C, a
character string
is defined as a contiguous sequence of characters terminated by, and including, the first null character (‘\0’). Hour 13, “Manipulating Strings,” introduces more details about strings.

In Listing 12.4, you see various ways to display an array of characters on the screen.

TYPE

LISTING 12.4

Printing an Array of Characters

1: /* 12L04.c: Printing out an array of characters */

2: #include

3:

4: main()

5: {

6: char array_ch[7] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’, ‘\0’};

7: int i;

8:

9: for (i=0; i<7; i++)

10: printf(“array_ch[%d] contains: %c\n”, i, array_ch[i]);

11: /*--- method I ---*/

12: printf( “Put all elements together(Method I):\n”);

13: for (i=0; array_ch[i] != ‘\0’ && i<7; i++)

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

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

Understanding Arrays

197

15: /*--- method II ---*/

16: printf( “\nPut all elements together(Method II):\n”);

17: printf( “%s\n”, array_ch);

Other books

Girl from Jussara by Hettie Ivers
The Reading Circle by Ashton Lee
The Dark Detective: Venator by Jane Harvey-Berrick
The Lightkeepers by Abby Geni
Native Dancer by John Eisenberg
The Wooden Chair by Rayne E. Golay
The Secret of Evil by Roberto Bolaño
Xquisite by Ruby Laska
Deadly Decision by Regina Smeltzer


readsbookonline.com Copyright 2016 - 2024