Structures in C

In this post we will have a look at Structures in C. We will first try to understand a problem statement and then see how structures can be helpful.

Ordinary variables like int, float, char, etc., can hold one piece of information and arrays can hold a number of pieces of information of the same data type. But quite often we deal with entities that are collection of dissimilar data types. For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we can follow two approaches:

  1. Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
  2. Use a structure variable.

Let us examine these two approaches one by one. For the sake of programming convenience assume that the names of books would be single character long. Let us begin with a program that uses arrays.

1) Construct individual arrays

main()
{
   char name[3] ;
   float price[3] ;
   int pages[3], i ;
   printf ( "\nEnter names, prices and no. of pages of 3 books\n" ) ;
   for ( i = 0 ; i <= 2 ; i++ )
      scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );
   printf ( "\nAnd this is what you entered\n" ) ;
   for ( i = 0 ; i &lt;= 2 ; i++ )
      printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}
 

And here is the sample run…

Enter names, prices and no. of pages of 3 books

A 100.00 354

C 256.50 682

F 233.70 512

And this is what you entered

A 100.000000 354

C 256.500000 682

F 233.700000 512

This approach no doubt allows you to store names, prices and number of pages. But as you must have realized, it is an unwieldy approach that obscures the fact that you are dealing with a group of characteristics related to a single entity—the book.

The program becomes more difficult to handle as the number of items relating to the book go on increasing. For example, we would be required to use a number of arrays, if we also decide to store name of the publisher, date of purchase of book, etc. To solve this problem, C provides a special data type—the structure.

2) Use a structure variable

A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type.  

main( )
{
   struct book
   {
      char name ;
      float price ;
      int pages ;
   } ;
   struct book b1, b2, b3 ;
   printf ( "\nEnter names, prices and no. of pages of 3 books\n" ) ;
   scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
   scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
   scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
   printf ( "\nAnd this is what you entered" ) 
   printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
   printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
   printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
}
 

And here is the output…

Enter names, prices and no. of pages of 3 books

A 100.00 354

C 256.50 682

F 233.70 512

And this is what you entered

A 100.000000 354

C 256.500000 682

F 233.700000 512

Let’s take another example. An embedded example!!

Let’s say you have multiple sensors installed in 5 different rooms – Temperature, Humidity, Luminosity, Motion and Sound sensors.

1) Construct individual arrays

One array for storing temperature, another for storing humidity and so on.

main()
{
   uint16_t temperature[5];
   uint8_t humidity[5]; 
   uint16_t luminosity[5]; 
   bool motion_detected[5];
   uint16_t sound_level[5];
 
   for (i=0; i<5;i++)
   {
      temperature[i] = read_temperature(i);
      humidity[i] = read_humidity(i);
      luminosity[i] = read_luminosity(i);
      motion_detected[i] = read_motion(i);
      sound_level[i] = read_sound(i)
   }
}

 

This approach no doubt allows you to store all the sensor values. But, as you can see, it hides the fact that you are dealing with a group of characteristics related to a single entity—the room.

The program becomes more difficult to handle as the number of items relating to the book go on increasing. For example, we would be required to use a number of arrays, if we more number of sensors or information related to a room. To solve this problem, C provides a special data type—the structure.

2) Use a structure variable

Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure help in constructing a complex data type which is more meaningful.

Think of it as an advanced version of an Array. An array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful. The following example illustrates the use of this data type. 

struct room
{
   uint16_t temperature;
   uint8_t humidity;
   uint16_t luminosity;
   bool motion_detected;
   uint16_t sound_level;
} ;
struct room r1, r2, r3, r4, r5;

 

The terms r1, r2, r3, r4, r5 are structure variables of type room. And the characteristics of this variables are declared in the structure, in this case, temperature, humidity, luminosity, motion and sound level. Now, each of these variables have the ability to store information of the related to the respective rooms. To store the temperature for room r1, we use the following:

r1.temperature;

 

Similarly for the other parameters

r1.humidity;
r1.luminosity;
r1.motion_detected;
r1.sound_level;

 

Similarly, parameters for all rooms can be updated or parameters of each room can be used.

Defining Structures in C

struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived datatypes.

Syntax:

struct [structure_tag]
{
    //member variable 1
    //member variable 2
    //member variable 3
    ...
}[structure_variables];

 

After the closing curly brace, we can specify one or more structure variables, but this is optional.

Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).

Example:

main( ) 
{ 
   struct room 
   {
      uint16_t temperature; 
      uint8_t humidity; 
      uint16_t luminosity; 
      bool motion_detected; 
      uint16_t sound_level; 
   } ; 
   struct room r1, r2, r3, r4, r5; 
}

 

Here struct room declares a structure to hold the sensor values of a room which consists of 5 member sensor values – temperature, humidity, luminosity, motion and sound level . These fields are called structure elements or members.

 

The following video will also help you understand structures better:

The members of Structures in C can be:

  • of the same data type
  • of different data types
  • arrays
  • another structure variable

In the next post, we will discuss about the memory layout of a structure.

Leave a Reply

Your email address will not be published. Required fields are marked *