E-learning

Computer-Based Training (CBT) or Internet-Based Training (IBT) or Web-Based Training (WBT) courses at BengalStudents website

Question and Answer

Q Why do you need structures?

A In practice, you need to collect and group data items that are relevant but of different types. The structure data type provides a convenient way to aggregate those differently typed data items.

Q Can you declare a structure and define a structure variable in a single statement?

Arrays of Structures

Arrays of Structures

In C, you can declare an array of a structure 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, with the structure data type of x. The array has eight elements.

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

Structures and Function Calls

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 rewrite the program in Listing 19.1 and create a function called DataReceive() in the program. The upgraded program is shown in Listing 19.3.

TYPE
Listing 19.3. Passing a structure to a function.

Referencing Structure Members with the Dot Operator

Referencing Structure Members with the Dot Operator

Now, let’s see how to reference a structure member. Given the structure data type of automobile and the structure of 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 variable called year, which is a member of the structure sedan.

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.

Exercises : Answer the following Question

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 E, “Answers to Quiz Questions and Exercises.”
Quiz

What are the values represented by the following enum names?

enum months { Jan, Feb, Mar, Apr,
May, Jun, Jul, Aug,
Sep, Oct, Nov, Dec };