Sams Teach Yourself C in 24 Hours (45 page)

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

It’s a string!

16

OUTPUT
It’s a string!

The sum returned by DataAdd(): 15

The sum returned by DataAdd(): 15

The purpose of the program in Listing 16.5 is to demonstrate how to pass two
ANALYSIS
pointers—an integer pointer that points to an integer array and a character pointer that references a character string—to two functions that are declared in lines 4

and 5.

Note that expressions such as char *ch and int *list are used as arguments in the function declarations, which indicates to the compiler that a char pointer and an int pointer are respectively passed to the functions ChPrint() and DataAdd().

Inside the main() function body, lines 8 and 9 declare a char array (str) that is initialized with a character string, and a char pointer variable (ptr_str). Line 10 declares and initializes an int array (list) with a set of integers. An int pointer variable, ptr_int, is declared in line 11.

The start address of the str array is assigned to the ptr_str pointer by the assignment statement in line 14. Then, the ptr_str pointer is passed to the ChPrint() function as the argument in line 15. According to the definition of ChPrint() in lines 27–30, the content of the str array whose start address is passed to the function as the argument is printed out by the printf() call inside the ChPrint() function in line 29.

In fact, you can still use the name of the str array as the argument and pass it to the ChPrint() function. Line 16 shows that the start address of the character array is passed to ChPrint() via the name of the array.

The statement in line 19 assigns the start address of the integer array list to the integer pointer ptr_int. Then, the ptr_int pointer is passed to the DataAdd() function in line 21, along with 5, which is the maximum number of elements contained by the list array. The max argument is used because the function can’t determine the size of the array given only the start address. From the definition of the DataAdd() function in lines 32–40, you can see that DataAdd() adds all the integer elements in list and returns the sum to the caller. Thereafter, the statement in lines 20 and 21 prints out the result returned from DataAdd().

21 067231861x CH16 1/25/00 10:36 AM Page 270

270

Hour 16

The expression in line 23 also invokes the DataAdd() function, but this time, the name of the list array is used as the argument to the function. Not surprisingly, the start address of the list array is passed to the DataAdd() function successfully, and the printf() statement in lines 22 and 23 displays the correct result on the screen.

Passing Multidimensional Arrays as Arguments

In Hour 12, “Understanding Arrays,” you learned about multidimensional arrays. In this section, you’re going to see how to pass multidimensional arrays to functions.

As you might have guessed, passing a multidimensional array to a function is similar to passing a one-dimensional array to a function. You can either pass the unsized format of a multidimensional array or a pointer that contains the start address of the multidimensional array to a function. Listing 16.6 is an example of these two methods.

TYPE

LISTING 16.6

Passing Multidimensional Arrays to Functions

1: /* 16L06.c: Passing multidimensional arrays to functions */

2: #include

3: /* function declarations */

4: int DataAdd1(int list[][5], int max1, int max2);

5: int DataAdd2(int *list, int max1, int max2);

6: /* main() function */

7: main()

8: {

9: int list[2][5] = {1, 2, 3, 4, 5,

10: 5, 4, 3, 2, 1};

11: int *ptr_int;

12:

13: printf(“The sum returned by DataAdd1(): %d\n”,

14: DataAdd1(list, 2, 5));

15: ptr_int = &list[0][0];

16: printf(“The sum returned by DataAdd2(): %d\n”,

17: DataAdd2(ptr_int, 2, 5));

18:

19: return 0;

20: }

21: /* function definition */

22: int DataAdd1(int list[][5], int max1, int max2)

23: {

24: int i, j;

25: int sum = 0;

26:

27: for (i=0; i

28: for (j=0; j

29: sum += list[i][j];

30: return sum;

31: }

21 067231861x CH16 1/25/00 10:36 AM Page 271

Applying Pointers

271

32: /* function definition */

33: int DataAdd2(int *list, int max1, int max2)

34: {

35: int i, j;

36: int sum = 0;

37:

38: for (i=0; i

39: for (j=0; j

40: sum += *(list + i*max2 + j);

41: return sum;

16

42: }

The following output is displayed on the screen of my computer after the executable (16L06.exe) is executed:

The sum returned by DataAdd1(): 30

OUTPUT
The sum returned by DataAdd2(): 30

At the beginning of the program in Listing 16.6, I declare two functions,
ANALYSIS
DataAdd1() and DataAdd2(), in lines 4 and 5. Note that the first argument to DataAdd1() in line 4 is the unsized array of list. In fact, list is a two-dimensional integer array declared in lines 9 and 10 inside the main() function body. The other two arguments, max1 and max2, are two dimension sizes of the list array.

As you can tell from the definition of DataAdd1() in lines 22–31, each element of the list array, expressed as list[i][j], is added and assigned to a local variable called sum that is returned at the end of the DataAdd1() function in line 30. Here i goes from 0 to max1 - 1, and j is within the range of 0 to max2 - 1.

The DataAdd1() function is called in line 14, with the name of the list array and the two dimension sizes, 2 and 5. The result returned by DataAdd1() is printed out by the statement in lines 13 and 14. So you see, passing a multidimensional array to a function is quite similar to passing a one-dimensional array to a function. The function, in this case, needs both dimension sizes to determine the total number of elements in the array.

Another way to do the job is to pass a pointer that contains the start address of a multidimensional array to a function. In this example, the DataAdd2() function is declared in line 5 with a pointer expression, int *list, as the function’s first argument. The definition of DataAdd2() is given in lines 33–42.

Note that in line 40, each element in the list array is fetched by moving the pointer to point to the memory location of the element. That is, the dereferenced pointer *(list +

i*max2 + j) evaluates to the value of an element that is located at row i and column j, if you imagine that the two-dimensional array is a matrix with both horizontal and vertical dimensions. Therefore, adding i*max2 to list calculates the address of row i (that is, 21 067231861x CH16 1/25/00 10:36 AM Page 272

272

Hour 16

skipping rows 0 through i-1), and then adding j calculates the address of element j (that is, column j) within the current row (i). In this example, the range of the row is from 0

to 1 (that is, a total of 2 rows); the range of the column is from 0 to 4 (that is, a total of 5

columns). See Figure 16.1.

The result returned by the DataAdd2() function is displayed on the screen by the printf() statement in lines 16 and 17.

FIGURE 16.1

Column

0

1

2

3

4

The two-dimensional

coordinate shows the

locations of the ele-

0

1

2

3

4

5

ments in the
list

Row

array.

1

5

4

3

2

1

Arrays of Pointers

In many cases, it’s useful to declare an array of pointers and access the contents pointed by the array by dereferencing each pointer. For instance, the following declaration declares an array of int pointers:

int *ptr_int[3];

In other words, the variable ptr_int is a three-element array of pointers to integers. In addition, you can initialize the array of pointers. For example:

int x1 = 10;

int x2 = 100;

int x3 = 1000;

ptr_int[0] = &x1;

ptr_int[1] = &x2;

ptr_int[2] = &x3;

Listing 16.7 shows another example. Here an array of pointers is used to access an array of strings.

TYPE

LISTING 16.7

Using an Array of Pointers to Character Strings

1: /* 16L07.c: Using an array of pointers */

2: #include

3: /* function declarations */

4: void StrPrint1(char **str1, int size);

5: void StrPrint2(char *str2);

21 067231861x CH16 1/25/00 10:36 AM Page 273

Applying Pointers

273

6: /* main() function */

7: main()

8: {

9: char *str[4] = {“There’s music in the sighing of a reed;”,

10: “There’s music in the gushing of a rill;”,

11: “There’s music in all things if men had ears;”,

12: “There earth is but an echo of the spheres.\n”

13: };

14: int i, size = 4;

15:

16

16: StrPrint1(str, size);

17: for (i=0; i

18: StrPrint2(str[i]);

19:

20: return 0;

21: }

22: /* function definition */

23: void StrPrint1(char **str1, int size)

24: {

25: int i;

26: /* Print all strings in an array of pointers to strings */

27: for (i=0; i

28: printf(“%s\n”, str1[i]);

29: }

30: /* function definition */

31: void StrPrint2(char *str2)

32: {

33: /* Prints one string at a time */

34: printf(“%s\n”, str2);

35: }

A piece of a poem written by Lord Byron is printed out after the executable (16L07.exe) of the program in Listing 16.7 is created and executed:

There’s music in the sighing of a reed;

OUTPUT
There’s music in the gushing of a rill;

There’s music in all things if men had ears;

There earth is but an echo of the spheres.

There’s music in the sighing of a reed;

There’s music in the gushing of a rill;

There’s music in all things if men had ears;

There earth is but an echo of the spheres.

Let’s first have a look at the array of pointers, str, which is declared and initial-ANALYSIS ized in lines 9–13 inside the main() function body of the program in Listing 16.7. As you can see, str is a four-element array of pointers to a set of character strings.

I have adopted four sentences of a poem written by Lord Byron and used them as four character strings in the program.

21 067231861x CH16 1/25/00 10:36 AM Page 274

274

Hour 16

You can access a character string by using a corresponding pointer in the array. In fact, there are two functions, StrPrint1() and StrPrint2(), in Listing 16.7. Both of them can be called to access the character strings. From the function declaration in line 4, you can see that the StrPrint1() function takes a pointer of pointers—that is, **str1, which is dereferenced inside the StrPrint1() function to represent the four pointers that point to the four character strings. The definition of StrPrint1() is in lines 23–29.

The StrPrint2() function, on the other hand, only takes a pointer variable as its argument, and prints out a character string referenced by the pointer. Lines 31–35 give the definition of the StrPrint2() function.

Now let’s move back to the main() function. The StrPrint1() function is called in line 16 with the name of the array of pointers, str, as the argument. StrPrint1() then displays the four sentences of Byron’s poem on the screen. The for loop in lines 17 and 18

does the same thing by calling the StrPrint2() function four times. Each time, the start address of a sentence is passed to StrPrint2(). Therefore, you see all the sentences of the poem printed on the screen twice..

Pointing to Functions

Before you finish the course for this hour, there is one more interesting thing you need to learn about: pointers to functions.

As with pointers to arrays, you can declare a pointer that is initialized with the left value of a function. (The left value is the memory address at which the function is located.) Then you can call the function via the pointer.

The program in Listing 16.8 is an example that declares a pointer to a function.

TYPE

LISTING 16.8

Pointing to a Function

1: /* 16L08.c: Pointing to a function */

2: #include

3: /* function declaration */

4: int StrPrint(char *str);

5: /* main() function */

6: main()

7: {

8: char str[24] = “Pointing to a function.”;

9: int (*ptr)(char *str);

10:

11: ptr = StrPrint;

12: if (!(*ptr)(str))

21 067231861x CH16 1/25/00 10:36 AM Page 275

Applying Pointers

275

13: printf(“Done!\n”);

14:

15: return 0;

16: }

17: /* function definition */

18: int StrPrint(char *str)

19: {

20: printf(“%s\n”, str);

21: return 0;

22: }

16

After the executable 16L08.exe of the program in Listing 16.8 is created and
OUTPUT
executed on my computer, the following output is shown on the screen: Pointing to a function.

ANALYSIS
Done!

As usual, a function declaration comes first in Listing 16.8. The StrPrint() function is declared with the int data type specifier and an argument of a char pointer in line 4.

Other books

At Lady Molly's by Anthony Powell
Madness by Marya Hornbacher
Intermission by Ashley Pullo
Raleigh's Page by Alan Armstrong
A Curious Career by Lynn Barber
Was it Good for You Too? by Naleighna Kai
A Woman of Courage by J.H. Fletcher