Sams Teach Yourself C in 24 Hours (52 page)

21: gets(info.name);

22: printf(“What’s your ID number?\n”);

23: scanf(“%d”, &info.id);

24:

25: printf(“\nHere are what you entered:\n”);

26: printf(“Name: %s\n”, info.name);

27: printf(“ID #: %04d\n”, info.id);

28:

29: return 0;

30: }

When the executable 19L02.exe is being run, the initial content saved in a structure is displayed. Then, I enter my answers to the questions and get the updated information shown on the screen:

Here is a sample:

OUTPUT

Employee Name: B. Smith

Employee ID #: 0001

What’s your name?

T. Zhang

What’s your ID number?

1234

25 067231861x CH19 4.10.2000 11:04 AM Page 319

Understanding Structures

319

Here are what you entered:

Name: T. Zhang

ID #: 1234

The purpose of the program in Listing 19.2 is to initialize a structure and then
ANALYSIS
ask the user to update the content held by the structure.

The structure data type, labeled as employee, is declared in lines 6–9. Then, the variable, info, is defined with the structure data type and initialized with the integer 1 and the string “B. Smith” in lines 11–14.

You can also combine the declaration, definition, and initialization of a structure into a single statement. Here’s an example:

struct employee {

int id;

char name[32];

} info = {

1,

“B. Smith”

};

The statements in lines 17 and 18 display the initial contents stored by the two members of the info structure on the screen. Then, lines 20–23 ask the user to enter his or her name and employee ID number and save them into the two structure members, name and id, respectively.

Before the end of the program, the updated contents contained by the two members are printed out by the statements in lines 26 and 27.

19

Again, the dot operator (.) is used in the program to reference the structure members.

Structures and Function Calls

The C language allows you to pass an entire structure to a function. In addition, a function can return a structure back to its caller.

To show you how to pass a structure to a function, I rewrote the program in Listing 19.1

and created a function called DataReceive() in the program. The upgraded program is shown in Listing 19.3.

25 067231861x CH19 4.10.2000 11:04 AM Page 320

320

Hour 19

TYPE

LISTING 19.3

Passing a Structure to a Function

1: /* 19L03.c Passing a structure to a function */

2: #include

3:

4: struct computer {

5: float cost;

6: int year;

7: int cpu_speed;

8: char cpu_type[16];

9: };

10: /* create synonym */

11: typedef struct computer SC;

12: /* function declaration */

13: SC DataReceive(SC s);

14:

15: main(void)

16: {

17: SC model;

18:

19: model = DataReceive(model);

20: printf(“Here are what you entered:\n”);

21: printf(“Year: %d\n”, model.year);

22: printf(“Cost: $%6.2f\n”, model.cost);

23: printf(“CPU type: %s\n”, model.cpu_type);

24: printf(“CPU speed: %d MHz\n”, model.cpu_speed);

25:

26: return 0;

27: }

28: /* function definition */

29: SC DataReceive(SC s)

30: {

31: printf(“The type of the CPU inside your computer?\n”);

32: gets(s.cpu_type);

33: printf(“The speed(MHz) of the CPU?\n”);

34: scanf(“%d”, &s.cpu_speed);

35: printf(“The year your computer was made?\n”);

36: scanf(“%d”, &s.year);

37: printf(“How much you paid for the computer?\n”);

38: scanf(“%f”, &s.cost);

39: return s;

40: }

After I run the executable, 19L03.exe, and enter my answers to the questions, I get the following output, which is the same as the output from the executable program of Listing 19.1:

25 067231861x CH19 4.10.2000 11:04 AM Page 321

Understanding Structures

321

The type of the CPU inside your computer?

OUTPUT

Pentium

The speed(MHz) of the CPU?

100

The year your computer was made?

1996

How much you paid for the computer?

1234.56

Here are what you entered:

Year: 1996

Cost: $1234.56

CPU type: Pentium

CPU speed: 100 MHz

The purpose of the program in Listing 19.3 is to show you how to pass a struc-ANALYSIS ture to a function. The structure in Listing 19.3, with the tag name of computer, is declared in lines 4–9.

Note that in line 11 the typedef keyword is used to define a synonym, SC, for struct computer. Then SC is used in the sequential declarations. Here, the structure and typedef are placed outside the main() function so that SC can be used in any function in the program.

The DataReceive() function is declared in line 13, with the structure of computer as its argument (that is, the synonym SC and the variable name s), so that a copy of the structure can be passed to the function.

In addition, the DataReceive() function returns the copy of the structure back to the caller after the content of the structure is updated. To do this, SC is prefixed to the func-19

tion in line 13 to indicate the data type of the value returned by the function.

The statement in line 17 defines the structure variable model with SC. The model structure is passed to the DataReceive() function in line 19, and then the value returned by the function is assigned back to model as well. Note that if the DataReceive() function return value is not assigned to model, the changes made to s in the function will not be evident in model.

The definition of the DataReceive() function is shown in lines 29–40, from which you can see that the new data values entered by the user are saved into the corresponding members of the structure that is passed to the function. At the end of the function, the copy of the updated structure is returned in line 39.

Then, back to the main() function of the program, lines 21–24 print out the updated contents held by the members of the structure. Because the program in Listing 19.3 is basically the same as the one in Listing 19.1, I see the same output on my screen after running the executable file 19L03.exe.

25 067231861x CH19 4.10.2000 11:04 AM Page 322

322

Hour 19

Referencing Structures with Pointers

As you can pass a pointer that refers to an array in a function call, you can also pass a pointer that points to a structure.

However, unlike passing a structure to a function, which sends an entire copy of the structure to the function, passing a pointer to a structure sends only the address of the structure to the function. The function can then use the address to access the structure members directly, avoiding the overhead of duplicating the structure. Therefore, it’s more efficient to pass a pointer to a structure, than it is to pass the structure itself to a function.

Accordingly, the program in Listing 19.3 can be rewritten to pass the DataReceive() function a pointer that points to the structure. The rewritten program is shown in Listing 19.4.

LISTING 19.4

Passing a Function with a Pointer that Points to a

TYPE

Structure

1: /* 19L04.c Pointing to a structure */

2: #include

3:

4: struct computer {

5: float cost;

6: int year;

7: int cpu_speed;

8: char cpu_type[16];

9: };

10:

11: typedef struct computer SC;

12:

13: void DataReceive(SC *ptr_s);

14:

15: main(void)

16: {

17: SC model;

18:

19: DataReceive(&model);

20: printf(“Here are what you entered:\n”);

21: printf(“Year: %d\n”, model.year);

22: printf(“Cost: $%6.2f\n”, model.cost);

23: printf(“CPU type: %s\n”, model.cpu_type);

24: printf(“CPU speed: %d MHz\n”, model.cpu_speed);

25:

26: return 0;

27: }

28: /* function definition */

29: void DataReceive(SC *ptr_s)

30: {

25 067231861x CH19 4.10.2000 11:04 AM Page 323

Understanding Structures

323

31: printf(“The type of the CPU inside your computer?\n”);

32: gets((*ptr_s).cpu_type);

33: printf(“The speed(MHz) of the CPU?\n”);

34: scanf(“%d”, &(*ptr_s).cpu_speed);

35: printf(“The year your computer was made?\n”);

36: scanf(“%d”, &(*ptr_s).year);

37: printf(“How much you paid for the computer?\n”);

38: scanf(“%f”, &(*ptr_s).cost);

39: }

Similarly, I obtain output that is the same as the one from the program in Listing 19.3

after I run the executable (19L04.exe) of the program in Listing 19.4:

The type of the CPU inside your computer?

OUTPUT

Pentium

The speed(MHz) of the CPU?

100

The year your computer was made?

1996

How much you paid for the computer?

1234.56

Here are what you entered:

Year: 1996

Cost: $1234.56

CPU type: Pentium

CPU speed: 100 MHz

The program in Listing 19.4 is almost identical to the one in Listing 19.3, except
ANALYSIS
that the argument passed to the DataReceive() function is a pointer defined with SC—that is, struct computer. (Refer to lines 11 and 13.) Also, the DataReceive()
19

function does not need to return a copy of the structure because the function can directly access and modify all members of the original structure, not a copy, via the pointer passed to it. That’s why the void keyword is prefixed to the function name in line 13.

The statement in line 17 defines the structure variable model. And in line 19, the address of the model structure is passed to the DataReceive() function by applying the address-of operator (&).

When you look at the definition of the DataReceive() function in lines 29–39, you see that the dereferenced pointer *ptr_s is used to reference the members of the model structure. For instance, to access the char array of cpu_type, (*ptr_s) is used in the (*ptr_s).cpu_type expression to indicate to the compiler that cpu_type is a member in the structure pointed to by the pointer ptr_s. Note that the dereferenced pointer *ptr_s has to be enclosed within the parentheses (( and )). This is because the default order of operator precedence would evaluate the . (dot) operator before the * operator, which in this case is not what we intend.

25 067231861x CH19 4.10.2000 11:04 AM Page 324

324

Hour 19

Another example is the expression &(*ptr_s).cpu_speed in line 34, which evaluates to the address of the cpu_speed member of the structure pointed to by the pointer ptr_s.

Again, the dereferenced pointer *ptr_s is surrounded by the parentheses (( and )).

The next subsection shows you how to use the arrow operator (->) to refer to a structure member with a pointer.

Referencing a Structure Member with
->

You can use the arrow operator -> to refer to a structure member associated with a pointer that points to the structure.

For instance, you can rewrite the (*ptr_s).cpu_type expression in Listing 19.4 with this:

ptr_s -> cpu_type

or you could replace the &(*ptr_s).cpu_speed expression with this:

&(ptr_s->cpu_speed)

Since the -> operator has higher precedence than the & operator, you can leave out the parentheses in the above expression, writing it instead like this:

&ptr_s->cpu_speed

Because of its better clarity, the -> operator is more frequently used in programs that access structure members via pointers to structures, rather than the dot operator. Exercise 3, later in this hour, gives you a chance to rewrite the entire program in Listing 19.4

using the -> operator.

Arrays of Structures

In C, you can declare an array of structures by preceding the array name with the structure name. For instance, given a structure with the tag name of x, the following statement:

struct x array_of_structure[8];

declares an array, called array_of_structure, of struct x. The array has eight elements, each element being a single instance of struct x.

The program shown in Listing 19.5 demonstrates how to use an array of structs by printing out two pieces of Japanese haiku and their authors’ names.

25 067231861x CH19 4.10.2000 11:04 AM Page 325

Understanding Structures

325

TYPE

LISTING 19.5

Using Arrays of Structures

1: /* 19L05.c Arrays of structures */

2: #include

3:

4: struct haiku {

5: int start_year;

6: int end_year;

7: char author[16];

8: char str1[32];

9: char str2[32];

10: char str3[32];

11: };

12:

13: typedef struct haiku HK;

14:

15: void DataDisplay(HK *ptr_s);

16:

17: main(void)

18: {

19: HK poem[2] = {

20: { 1641,

21: 1716,

22: “Sodo”,

23: “Leading me along”,

24: “my shadow goes back home”,

25: “from looking at the moon.”

26: },

27: { 1729,

28: 1781,

29: “Chora”,

19

30: “A storm wind blows”,

31: “out from among the grasses”,

Other books

Protected by the Major by Anne Herries
STOLEN by Silver, Jordan
The Conquering Tide by Ian W. Toll
The Finishing School by Gail Godwin
Kristy's Mystery Admirer by Ann M. Martin
Dark Universe by Devon Herrera


readsbookonline.com Copyright 2016 - 2024