Sams Teach Yourself C in 24 Hours (51 page)

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

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.”

18

Quiz

1. What are the values represented by the following enum names?

enum months { Jan, Feb, Mar, Apr,

May, Jun, Jul, Aug,

Sep, Oct, Nov, Dec };

2. What are the values represented by the following enum names?

enum tag { name1,

name2 = 10,

name3,

name4 };

3. Which of the following statements have equivalent variable declarations?

• typedef long int BYTE32; BYTE32 x, y, z;

• typedef char *STRING[16]; STRING str1, str2, str3;

• long int x, y, z;

• char *str1[16], *str2[16], *str3[16];

4. Can you pass some command-line arguments to a main() function that has the following definition?

int main(void)

{

. . .

}

23 067231861x CH18 1/25/00 10:31 AM Page 310

310

Hour 18

Exercises

1. Write a program to print out the values represented by the enumerated names declared in Quiz question 2 in this hour.

2. Given the following declarations:

typedef char WORD;

typedef int SHORT;

typedef long LONG;

typedef float FLOAT;

typedef double DFLOAT;

write a program to measure the sizes of the synonyms to the data types.

3. Rewrite the program in Listing 18.4. This time, add integers starting at the value of MIN_NUM instead of the value of MAX_NUM.

4. Write a program that accepts command-line arguments. If the number of command-line arguments, not including the name of the executable itself, is less than two, print out the usage format of the program and ask the user to reenter the command-line arguments. Otherwise, display all command-line arguments entered by the user.

24 067231861x pt 5 1/25/00 11:12 AM Page 311

PART V

Structure, Union, File I/O,

and More

Hour

19 Understanding Structures

20 Understanding Unions

21 Reading and Writing with Files

22 Using Special File Functions

23 Compiling Programs: The C Preprocessor

24 Where Do You Go from Here?

24 067231861x pt 5 1/25/00 11:12 AM Page 312

25 067231861x CH19 4.10.2000 11:04 AM Page 313

HOUR 19

Understanding

Structures

The art of programming is the art of organizing complexity.

—W. W. Dijkstra

In Hour 12, “Understanding Arrays,” you learned how to store data of the same type into arrays. In this hour, you’ll learn to use structures to collect data items that have different data types. The following topics are covered in this lesson:

• Declaring and defining structures

• Referencing structure members

• Structures and pointers

• Structures and functions

• Arrays of structures

25 067231861x CH19 4.10.2000 11:04 AM Page 314

314

Hour 19

What Is a Structure?

As you’ve learned, arrays can be used to collect groups of variables of the same type.

The question now is how to aggregate pieces of data that are not identically typed.

The answer is that you can group variables of different types with a data type called a
structure
. In C, a structure collects different data items in such a way that they can be referenced as a single unit.

There are several major differences between an array and a structure. Besides the fact that data items in a structure can have different types, each data item has its own name instead of a subscript value. In fact, data items in a structure are called
members
of the structure.

The next two subsections teach you how to declare structures and define structure variables.

Declaring Structures

The general form to declare a structure is

struct struct_tag {

data_type1 variable1;

data_type2 variable2;

data_type3 variable3;

.

.

.

};

Here struct is the keyword used in C to start a structure declaration. struct_tag is the tag name of the structure. variable1, variable2, and variable3 are the members of the structure. Their data types are specified respectively by data_type1, data_type2, and data_type3. As you can see, the declarations of the members have to be enclosed within the opening and closing braces ({ and }) in the structure declaration, and a semicolon (;) has to be included at the end of the declaration.

The following is an example of a structure declaration:

struct automobile {

int year;

char model[8];

int engine_power;

float weight;

};

25 067231861x CH19 4.10.2000 11:04 AM Page 315

Understanding Structures

315

Here struct is used to start a structure declaration. automobile is the tag name of the structure. In this example, there are three types of variables, char, int, and float. The variables have their own names, such as year, model, engine_power, and weight.

Note that a structure tag name, like automobile, is the name of a structure. The compiler uses the tag name to identify the structure labeled by that tag name.

Defining Structure Variables

After declaring a structure, you can define the structure variables. For instance, the following structure variables are defined with the structure data type of automobile from the previous section:

struct automobile sedan, pick_up, sport_utility;

Here three structure variables, sedan, pick_up, and sport_utility, are defined by the structure of automobile. All these three structure variables contain the four members of the structure automobile.

Also, you can combine the structure declaration and definition into one statement like this:

struct automobile {

int year;

char model[8];

int engine_power;

float weight;

} sedan, pick_up, sport_utility;

Here three structure variables, sedan, pick_up, and sport_utility, are defined along
19

with the structure automobile in the single statement.

Referencing Structure Members with the Dot

Operator

Now, let’s see how to reference a structure member. Given the structure automobile and the structure variable sedan, for instance, I can access its member, year, and assign an integer to it in the following way:

sedan.year = 1997;

Here the structure name and its member’s name are separated by the dot (.) operator so that the compiler knows that the integer value of 1997 is assigned to the member called year, which is a member of the structure variable called sedan.

25 067231861x CH19 4.10.2000 11:04 AM Page 316

316

Hour 19

Likewise, the following statement assigns the start address of the character array of model, which is another member of the structure variable sedan, to a char pointer ptr: ptr = sedan.model;

The program in Listing 19.1 gives another example to reference the members of a structure.

TYPE

LISTING 19.1

Referencing the Members of a Structure

1: /* 19L01.c Access to structure members */

2: #include

3:

4: main(void)

5: {

6: struct computer {

7: float cost;

8: int year;

9: int cpu_speed;

10: char cpu_type[16];

11: } model;

12:

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

14: gets(model.cpu_type);

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

16: scanf(“%d”, &model.cpu_speed);

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

18: scanf(“%d”, &model.year);

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

20: scanf(“%f”, &model.cost);

21:

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

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

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

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

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

27:

28: return 0;

29: }

I have the following output shown on the screen after I run the executable (19L01.exe) of the program in Listing 19.1 and enter my answers to the questions (in the output, the bold characters or numbers are the answers entered from my keyboard):

25 067231861x CH19 4.10.2000 11:04 AM Page 317

Understanding Structures

317

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.1 is to show you how to reference
ANALYSIS
members of a structure. As you can see from the program, there is a structure called model that is defined with a type of struct computer in lines 6–11. The structure has one float variable, two int variables, and one char array. The statement in line 13

asks the user to enter the type of the CPU (central processing unit) used inside his or her computer. Then, line 14 receives the string of the CPU type entered by the user and saves the string into the char array called cpu_type. Because cpu_type is a member of the model structure, the model.cpu_type expression is used in line 14 to reference the member of the structure. Note that the dot operator (.) is used to separate the two names in the expression.

Lines 15 and 16 ask for the CPU speed and store the value of an integer entered by the user to another member of the model structure—the int variable cpu_speed. Note that in line 16, the address-of operator (&) is prefixed to the model.cpu_speed expression inside
19

the scanf() function because the argument should be an int pointer.

Likewise, lines 17 and 18 receive the value of the year in which the user’s computer was made, and lines 19 and 20 get the number for the cost of the computer. After the execution, the int variable year and the float variable cost in the model structure contain the corresponding values entered by the user.

Then, lines 23–26 print out all values held by the members of the model structure. From the output, you can tell that each member of the structure has been accessed and assigned a number or string correctly.

Initializing Structures

A structure can be initialized by a list of data called
initializers
. Commas are used to separate data items in a list of data.

25 067231861x CH19 4.10.2000 11:04 AM Page 318

318

Hour 19

Listing 19.2 contains an example of initializing a structure before it’s updated by the user.

TYPE

LISTING 19.2

Initializing a Structure

1: /* 19L02.c Initializing a structure */

2: #include

3:

4: main(void)

5: {

6: struct employee {

7: int id;

8: char name[32];

9: };

10: /* structure initialization */

11: struct employee info = {

12: 1,

13: “B. Smith”

14: };

15:

16: printf(“Here is a sample:\n”);

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

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

19:

20: printf(“What’s your name?\n”);

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

Other books

Damaged by Elizabeth McMahen
Monument to the Dead by Sheila Connolly
Alien Enigma by Bain, Darrell, Teora, Tony
A Game Most Dangerous by Megan Derr
Half Way to Love by Lockwood, Tressie
Weep No More My Lady by Mary Higgins Clark