Structure in c programming


  • A structure is a collection of one or more variables of different data types, grouped together under a single name.
  • It is a derived data type to be arranged in a group of related data items of different data types.
  • It is a user-defined data type because the user can decide the data types to be included in the body of a structure. By using structures, we can make a group of variables, arrays and pointers.
  • Structure helps to construct a complex data type which is more meaningful.
  • It is somewhat similar to an Array, but 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.

How to create a structure in C Programming

    We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type.

    struct struct_name {
       DataType member1_name;
       DataType member2_name;
       DataType member3_name;
       …
    };
    

Array of structures

  • As we know, array is a collection of same data types. In the same way, we can also define array of structure.
  • In such type of array, every element is of structure type. Array of structure can be declared as follows.
  • struct time
    
    {
    
    int second;
    
    int minute;
    
    int hour;
    
    } t[3];
  • In the above example, t[3] is an array of three elements containing three objects of time structure. Each element of t[3] has structure of time with three members that are second, minute and hour.

    Example:

    #include <stdio.h>
    
    /* Created a structure here. The name of the structure is * StudentData. */
    struct StudentData{
        char *stu_name;
        int stu_id;
        int stu_age;
    };
    int main()
    {
         /* student is the variable of structure StudentData*/
         struct StudentData student;
    
         /*Assigning the values of each struct member here*/
         student.stu_name = "Crazy";
         student.stu_id = 042019;
         student.stu_age = 21;
    
         /* Displaying the values of struct members */
         printf("Student Name is: %s", student.stu_name);
         printf("\nStudent Id is: %d", student.stu_id);
         printf("\nStudent Age is: %d", student.stu_age);
         return 0;
    }
    

    Output:

    Student Name is: Crazy
    Student Id is: 042019
    Student Age is: 21