Structures

The basic and derived types are too homogeneous for some situations, such as saving a date where the month might be a three character string and the day of the month and the year are integers. Structures allow the programmer to refer to a collection of such inhomogeneous variables collectively. The above situation will be handled by,
   struct date
   {
      char month[4];
      int  day,
           year;
   };
This defines a new structure type named date . The struct date type can be used in almost any way the basic types can be used. Thus the above definition acts like the definition of a new data type. Later a variable can be defined as in
   struct date my_birthday;

The individual fields in a structure are obtained by using the "." operator. For example,

   my_birthday.day = 1;     // Set the day of the month
   cout << my_birthday.day;   // print it out

Using pointers with structures is made easier by allowing an additional "->" operator to refer to a member of the structure pointed to by the pointer variable. Therefore the following two are equivalent.

   (*(pointer_to_date)).day
   pointer_to_date -> day

Example :

   pointer_to_date = &my_birthday;   // Initialize pointer
   pointer_to_date -> day = 3;    // Change day to 3
   cout << my_birthday.day;          // Will print out 3 not 1

Please feel free to question or discuss any part of this section. These questions and discussions are also archived.
(C) 1994 naren
Distributed without any warranty under GNU GPL
nan2@cortex.eecs.lehigh.edu
Last modified: Thu Feb 9 20:09:26 1995