Menu

Structures in C

  • A structure is a data structure, where individual elements can be of different data types.
  • A single structure may contain data elements of different types, ie it is possible that a single structure to contain integer elements,floating point elements, charecter elements etc.
  • A structure combines logically related data items into a sngle unit.

Syntax

    struct structure_name{
       datatype member1;
       datatype member2;
       ...........................
       ..........................
       datatype membern;
    };

Example

    struct account{
      int acc_no;
      int acc_type;
      char name[20];
      float avail_bal;
    };
  • struct is the keyword.
  • struct declares a structure to hold the details of four fields(namely acc_no, acc_type,name and(avail_bal).
  • account is the name of the structure.
  • acc_no is of type int, acc_type is of type int, name is of type char and avail_bal is of type float.

Structure Declaration

       struct structurename var1,var2....varn;

Example

       struct account ac1; //when structure variables are declared,memory is allocated to them.

Accessing structure variables

  • We use member access operator(.) to access any member of a structure.
  • The dot operator is placed in between structure variable and member name.

Syntax

       structurevariable.membername

Example

   #include<stdio.h>
   struct account
   {
     int acc_no;
     int acc_type;
     char name[20];
     float avail_bal;
   };
   main(){ 
     account acc;
     printf("enter the account number:");
     scanf("%d",&acc.acc_no);
     printf("Enter the account type:");
     scanf("%d",&acc.acc_type);
     printf("enter the account name:");
     scanf("%s",&acc.name);
     printf("enter the available balance:");
     scanf("%d",&acc.avail_bal);
     printf("The account number is %d",acc.acc_no);
     printf("The account type is %d",acc.acc_type);
     printf("The account name is %s",acc.acc_name);
     printf("The available balance is %d",acc.avail_bal);
   }

Output

      0 1 2 3 4 6 7 8 9

Structure Initialization

  • A structure can be initialized as follows.

                    structurename var={values};

Example

       account acc={10,114,"rajiv",7000};