Sams Teach Yourself C in 24 Hours (36 page)

• C supports multidimensional arrays, too. An empty pair of brackets (the array sub-12

script operator—[ and ]) indicates a dimension.

• The compiler can automatically calculate the memory space needed by an unsized array.

In the next lesson you’ll learn more about strings in C.

Q&A

Q Why do you need to use arrays?

A
In many cases, you need to declare a set of variables that are of the same data type.

Instead of declaring each variable separately, you can declare all variables collectively in the format of an array. Each variable, as an element of the array, can be accessed either through the array element reference or through a pointer that references the array.

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

204

Hour 12

Q What is the minimum index in an array?

A
In C, the minimum index of a one-dimensional array is 0, which marks the first element of the array. For instance, given an integer array,

int array_int[8];

the first element of the array is array_int[0].

Likewise, for a multidimensional array, the minimum index of each dimension starts at 0.

Q How do you reference an array by using a pointer?

A
You can use a pointer to reference an array by assigning the start address of an array to the pointer. For example, given a pointer variable ptr_ch and a character array array_ch, you can use one of the following statements to reference the array by the pointer:

ptr_ch = array_ch;

or

ptr_ch = &array_ch[0];

Q What can the null character do?

A
The null character (‘\0’) in C can be used to mark the end of a string. For instance, the printf() function keeps putting the next character on the screen until the null character is encountered. Also, the null character always evaluates to a value of zero.

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix B, “Answers to Quiz Questions and Exercises.”

Quiz

1. What does the following statement do?

int array_int[4] = {12, 23, 9, 56};

2. Given an array, int data[3], what’s wrong with the following initialization?

data[1] = 1;

data[2] = 2;

data[3] = 3;

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

Understanding Arrays

205

3. How many dimensions do the following arrays have?

• char array1[3][19];

• int array2[];

• float array3[][8][16];

• char array4[][80];

4. What’s wrong with the following declaration?

char list_ch[][] = {

‘A’, ‘a’,

‘B’, ‘b’,

‘C’, ‘c’,

‘D’, ‘d’,

Exercises

1. Given this character array:

char array_ch[5] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};

write a program to display each element of the array on the screen.

2. Rewrite the program in Exercise 1, but this time use a for loop to initialize the character array with ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’, and then print out the value of each element in the array.

3. Given this two-dimensional unsized array:

char list_ch[][2] = {

‘1’, ‘a’,

‘2’, ‘b’,

‘3’, ‘c’,

12

‘4’, ‘d’,

‘5’, ‘e’,

‘6’, ‘f’};

write a program to measure the total bytes taken by the array, and then print out all elements of the array.

4. Rewrite the program in Listing 12.5. This time put a string of characters, I like C!, on the screen.

5. Given the following array:

double list_data[6] = {

1.12345,

2.12345,

3.12345,

4.12345,

5.12345};

use the two equivalent ways taught in this lesson to measure the total memory space taken by the array, and then display the results on the screen.

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

17 067231861x CH13 1/25/00 10:29 AM Page 207

HOUR 13

Manipulating Strings

I have made this letter longer than usual, because I lack the time to make it
short.

—B. Pascal

In the last hour’s lesson you learned how to use arrays to collect variables of the same type. You also learned that a character string is actually a character array, with a null character \0 marking the end of the string. In this lesson you’ll learn more about strings, and C functions that can be used to manipulate strings. The following topics are covered:

• Declaring a string

• The length of a string

• Copying strings

• Reading strings with scanf()

• The gets() and puts() functions

17 067231861x CH13 1/25/00 10:29 AM Page 208

208

Hour 13

Declaring Strings

This section teaches you how to declare and initialize strings, as well as the difference between string constants and character constants. First, let’s review the definition of a string.

What Is a String?

As introduced in Hour 12, “Understanding Arrays,” a
string
is a character array, with a null character (\0) used to mark the end of the string. (The length of a string can be shorter than its character array.)

For instance, a character array, array_ch, declared in the following statement, is considered as a character string:

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

In C, the null character is used to mark the end of a string, and it always evaluates to 0. C

treats \0 as one character. Each character in a string takes only 1 byte.

A series of characters enclosed in double quotes (“”) is called a
string constant
. The C

compiler will automatically add a null character (\0) at the end of a string constant to indicate the end of the string.

For example, the character string “A character string.” is considered a string constant; so is “Hello!”.

Initializing Strings

As taught in the last lesson, a character array can be declared and initialized like this: char arr_str[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’};

Here the array arr_str is treated as a character array. However, if you add a null character (\0) into the array, you can have the following statement:

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

Here the array arr_str is expanded to hold seven elements; the last element contains a null character. Now, the character array arr_str is considered a character string because of the null character that is appended (added to the end) of the character data.

You can also initialize a character array with a string constant, instead of a list of character constants. For example, the following statement initializes a character array, str, with a string constant, “Hello!”:

char str[7] = “Hello!”;

17 067231861x CH13 1/25/00 10:29 AM Page 209

Manipulating Strings

209

The compiler will automatically append a null character (\0) to the end of “Hello!”, and treat the character array as a character string. Note that the size of the array is specified to hold up to seven elements, although the string constant has only six characters enclosed in double quotes. The extra space is reserved for the null character that will be added later by the compiler.

You can declare an unsized character array if you want the compiler to calculate the total number of elements in the array. For instance, the following statement: char str[] = “I like C.”;

initializes an unsized character array:, str, with a string constant. Later, when the compiler sees the statement, it will figure out the total memory space needed to hold the string constant plus an extra null character added by the compiler itself.

If you like, you can also declare a char pointer and then initialize the pointer with a string constant. The following statement is an example:

char *ptr_str = “I teach myself C.”;

Don’t specify the size of a character array as too small. Otherwise, it cannot hold a string constant plus an extra null character. For instance, the following declaration is considered illegal:

char str[4] = “text”;

Note that many C compilers will not issue a warning or an error message on this incorrect declaration. The runtime errors that could eventually arise as a result could be very difficult to debug. Therefore, it’s your responsibility to make sure to specify enough space for a string.

The following statement is a correct one, because it specifies the size of the character array str that is big enough to hold the string constant plus an extra null character:

char str[5] = “text”;

13

String Constants versus Character Constants

As you already know, a string constant is a series of characters enclosed in double quotes (“ “). On the other hand, a character constant is a character enclosed in single quotes (‘ ‘).

When a character variable ch and a character array str are initialized with the same character, x, such as the following:

17 067231861x CH13 1/25/00 10:29 AM Page 210

210

Hour 13

char ch = ‘x’;

char str[] = “x”;

1 byte is reserved for the character variable ch, and two bytes are allocated for the character array str. The reason that an extra byte is needed for str is that the compiler has to append a null character to the array.

Another important thing is that a string, since it is an array, is really a char pointer.

Therefore, you can assign a character string to a pointer variable directly, like this: char *ptr_str;

ptr_str = “A character string.”;

However, you cannot assign a character constant to the pointer variable, as shown in the following :

ptr_str = ‘x’; /* It’s wrong. */

In other words, the character constant ‘x’ contains a right value, and the pointer variable ptr_str expects a left value. But C requires the same kinds of values on both sides of an assignment operator =.

It’s legal to assign a character constant to a dereferenced char pointer like this: char *ptr_str;

*ptr_str = ‘x’;

Now the values on both sides of the = operator are of the same type.

The program in Listing 13.1 demonstrates how to initialize, or assign, character arrays with string constants.

LISTING 13.1

Initializing Strings

1: /* 13L01.c: Initializing strings */

2: #include

3:

4: main()

5: {

6: char str1[] = {‘A’, ‘ ‘,

7: ‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’, ‘ ‘,

8: ‘c’, ‘o’, ‘n’, ‘s’, ‘t’, ‘a’, ‘n’, ‘t’, ‘\0’};

9: char str2[] = “Another string constant”;

10: char *ptr_str;

11: int i;

12:

13: /* print out str1 */

14: for (i=0; str1[i]; i++)

15: printf(“%c”, str1[i]);

17 067231861x CH13 1/25/00 10:29 AM Page 211

Manipulating Strings

211

16: printf(“\n”);

17: /* print out str2 */

18: for (i=0; str2[i]; i++)

19: printf(“%c”, str2[i]);

20: printf(“\n”);

21: /* assign a string to a pointer */

22: ptr_str = “Assign a string to a pointer.”;

23: for (i=0; *ptr_str; i++)

24: printf(“%c”, *ptr_str++);

25: return 0;

26: }

The following output is displayed after the executable 13L01.exe of the program in Listing 13.1 is created and run.

A string constant

OUTPUT

Another string constant

Assign a string to a pointer.

As you can see from Listing 13.1, there are two character arrays, str1 and str2,
ANALYSIS
that are declared and initialized in lines 6–9. In the declaration of str1, a set of character constants, including a null character, is used to initialize the array. For str2, a string constant is assigned to the array in line 9. The compiler will append a null character to str2. Note that both str1 and str2 are declared as unsized arrays for which the compiler will automatically figure out how much memory is needed. The statement in line 10 declares a char pointer variable, ptr_str.

The for loop in lines 14 and 15 then prints out all the elements in str1. Because the last element contains a null character (\0) that is evaluated as 0, str1[i] is used as the conditional expression of the for statement. The expression str1[i] evaluates to nonzero for each element in str1 except the one holding the null character. After the execution of the for loop, the string A string constant is shown on the screen..

Likewise, another for loop in lines 18 and 19 displays the string constant assigned to
13

str2 by putting every element of the array on the screen. Because the compiler appends a null character to the array, the expression str2[i] is evaluated in the for statement.

Other books

Battle of Lookout Mountain by Gilbert L. Morris
Getting Even by Woody Allen
On a Clear Day by Walter Dean Myers
Vicki's Work of Heart by Rosie Dean
When Solomon Sings by Kendra Norman-Bellamy
Wicked by Susan Johnson
Chasing Jenna by Micki Fredricks
Red Gold by Alan Furst


readsbookonline.com Copyright 2016 - 2024