Categories
b. Derived Data Type

Structure

A structure is a user-defined data type in C that allows you to combine members of different types under a single name (or the struct type). The reason why it is called a user-defined data type is that the variables of different types are clubbed together under a single structure, which can be defined according to the user’s choice. 

Consider a situation where you want to store a record of a book. The book will have properties like name, author, and genre. You can create three variables to store this information. But what if you need to store records of 10 books. Then creating 3 separate variables for each book would not be a practical solution. This is where a structure can be a great solution. A single structure book can be created having three members: name, author, and genre. This structure can be used for all 10 books. 

Syntax 

// define a structure.

struct structure_name 

{

    data_type var1;

    data_type var2;    

};

Description of the Syntax

  • struct: The definition of a structure includes the keyword struct followed by its name. All the items inside it are called its members and after being declared inside a structure. 
  • data_type: Each variable can have a different data type. Variables of any data type can be declared inside a structure.
  • The definition of a structure ends with a semicolon at the end.

Example

The following example illustrates structure in C.

#include<stdio.h>  

#include <string.h>  

// define a "user-defined" structure.

struct book      

{

    // declare members of the structure.

int id;      

char name[25];

char author[50];

char genre[20];      

};

int main( )    

{

// declare a variable of the book type.

struct book b1; 

   //store the information of the books.    

b1.id = 10; 

strcpy(b1.name, "Dummy");  

strcpy(b1.author, "Dummy Author"); 

strcpy(b1.genre, "Science Fiction");

   // print the information.    

printf( "The id is: %d\n", b1.id);    

printf( "The name of the book is: %s\n", b1.name);    

printf( "The author of the book is: %s\n", b1.author);    

printf( "The genre of the book is: %s\n", b1.genre);     

return 0;  

}

Data_Types_in_C_9

In the above example, a structured book is defined with 4 member variables: id, name, author, and genre. Now a separate copy of these 4 members will be allocated to any variable of the book type. So, the variable b1 also has its own copy of these 4 variables which are used to store the information about this book.

Leave a Reply

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