C Programming Language Tutorial - C Language Structures and Unions

Structure

Structure is the group of mixed data type variables, where you can declare multiple variable of different data type’s variable under a name (structure). A structure represents the multiple variables. It is used when you have multiple variables to declare & access.

Structure Declaration: [type 1]
    struct <structure-name>
    {
        structure-member-1;
        structure-member-2;
        structure-member-3;
        ….
        structure-member-N;
    }[<structure-variable>];
    
  • struct is the keyword to declare an structure.
  • <structure-name> is the name of the structure.
  • structure-members are the members of the structure of the structure of different types.
  • [<structure-variable>] is the variable of structure, with this variable we can access all structure members. It is options here, we can declare structure variable without structure declaration.


Structure variable declaration
        struct <structure-name> <structure-variable-1>,<structure-variable-2>,..;
    


Example of structure declaration & structure variable declaration:
    /*structure declaration*/
    struct student
    {
	    char name[30];
	    int rollNo;
	    float percentage;
    };
    /*structure variable declaration*/
    struct student std1,std2;
    
Here, student is the structure name and std1, std2 are the two structure variables, which have name, rollNo and percentage variables.

Structure Declaration: [type 2]
    struct <structure-name>
    typedef struct
    {
	    structure-member-1;
	    structure-member-2;
	    structure-member-3;
	    …
	    structure-member-N;
    }<structure-name>
    


Structure variable declaration
        <structure-name> <structure-variable1>,<structure-variable2>,…;
    
Here, you do not need to use struct keyword to declare structure variable.

Example of structure declaration & structure variable declaration:
    /*structure declaration*/
    typedef struct 
    {
	    char name[30];
	    int rollNo;
	    float percentage;
    } student;
    /*structure variable declaration*/
    student std1,std2;
    


Structure Initialization with declaration:
    struct student std1={"Sachin", 1234 , 78.23}, std2={"Mr. XYZ", 456, 88.98};
    


Accessing structure members:
You can access structure members using the DOT/PERIOD (.) operator.
    <structure-variable>.<structure-member>;
    


Consider the example
    #include <stdio.h>
    #include <string.h>

    /*structure declaration*/
    struct student
    {
	    char	name[30];
	    int		rollNo;
	    float	percentage;
    };
    int main()
    {
	    struct student std1,std2;

	    // std1 initialization
	    strcpy(std1.name,"Sacin");
	    std1.rollNo=123;
	    std1.percentage=75.23f;

	    // std2 initialization
	    strcpy(std2.name,"Mr. Abc");
	    std2.rollNo=456;
	    std2.percentage=85.00f;

	    // print details of students
	    printf("Student 1 \nName: %s, Roll Number : %d, Percentage : %.2f%%\n",
        std1.name,std1.rollNo, std1.percentage);
	    printf("Student 2 \nName: %s, Roll Number : %d, Percentage : %.2f%%\n",
        std2.name,std2.rollNo, std2.percentage);
        return 0;
    }
    
Output
    
    Student 1
    Name: Sacin, Roll Number : 123, Percentage : 75.23%
    Student 2
    Name: Mr. Abc, Roll Number : 456, Percentage : 85.00%
    


Array of structures

We can also declare a structure variable as an array and then we can work with the multiple records of different types.

    //Syntax
    struct <structure-variable>[<MAX-SIZE>];
    //Example
    struct std[5];
    

Consider the example - read and print the records of N employees
        #include <stdio.h>
        #include <string.h>

        /*structure declaration*/
        struct employee
        {
	        char	name[30];
	        int		empId;
	        int		salary;
        };
        int main()
        {
	        struct employee emp[10];
	        int n,loop;

	        printf("Enter total number of employees: ");
	        scanf("%d",&n);

	        for(loop=0;loop < n;loop++)
	        {
		        printf("\nEnter details of employee [%d] :\n",loop+1);
		        printf("Name ? : ");
		        fflush(stdin);
		        gets(emp[loop].name);

		        printf("Employee ID ? : ");
		        scanf("%d",&emp[loop].empId);

		        printf("Employee Salary ? : ");
		        scanf("%d",&emp[loop].salary);
	        }

	        printf("\nEntered details of employees:\n");
	        for(loop=0;loop < n;loop++)
	        {
		        printf("\nEmployee [%d] :",loop+1);
		        printf("Emp Id : %d, Emp Name : %s, Salary : %d\n",
                emp[loop].empId, emp[loop].name, emp[loop].salary);
	        }
          getch();
          return 0;
        }
        
Output

        Enter total number of employees: 2

        Enter details of employee [1] :
        Name ? : Namita
        Employee ID ? : 101
        Employee Salary ? : 32000

        Enter details of employee [2] :
        Name ? : Radhika
        Employee ID ? : 102
        Employee Salary ? : 28750

        Entered details of employees:
        Employee [1] :Emp Id : 101, Emp Name : Namita, Salary : 32000
        Employee [2] :Emp Id : 102, Emp Name : Radhika, Salary : 28750
        


Passing structure as a function argument

We have discussed previously about User define functions and it’s arguments, arguments are the variables which pass to the function at the time of calling to share values and references in the function’s definition.
A structure can also be passed into the function like other normal variables, but there is little difference in the function declaration and definition section.

Declaration
    <return-type> functionName(struct <structure-name> <formal-structure-variable>,..);
    
    <return-type> functionName(struct <structure-name> <formal-structure-variable>,..)
    {
        Statements;
    }
    
  • <structure-name> is the name of structure which is defined outside of the function declaration.
  • <formal-structure-variable> is the name of structure variable, which may be different from actual stucrure variable name.

Consider the example
    #include<string.h>
    #include<stdio.h>

    /* structure declaration*/
    struct Item
    {
	    int id;
	    char name[30];
	    float price;
    };

    /*functio to get deatils of an item*/
    void getItemDetail(struct Item itm);


    int main()
    {
	    struct Item item;	// item is the structure variable

	    getItemDetail(item);
	    return 0;
    }

    /*function definition*/
    void getItemDetail(struct Item itm)
    {
	
	    printf("Enter detail of the Item :\n");
	    printf("Enter Item Id: ");
	    scanf("%d",&itm.id);
	    printf("Enter Item Name : ");
	    fflush(stdin);
	    gets(itm.name);
	    printf("Enter Item Price : ");
	    scanf("%f",&itm.price);
	    printf("\nEntered Item detail is :\n");
	    printf("\nID: %d, Name : %s, Price : %.2f",itm.id, itm.name,itm.price);
    }
    
Output

    Enter detail of the Item :
    Enter Item Id: 111
    Enter Item Name : DOVE
    Enter Item Price : 57.75

    Entered Item detail is :
    ID: 111, Name : DOVE, Price : 57.75
    


Calling function with Call by Reference:
In the previous example there is a single function to get and put the details of an item, if you want to create two separate functions getItemDetail() and putItemDetail() to get and put the item details. If you call the function using call by value, you will not get proper result. Consider the examples
        
    #include<string.h>
    #include<stdio.h>
    
    /* structure declaration*/
    struct Item
    {
        int id;
        char name[30];
        float price;
    };
 
    /*functio to get deatils of an item*/
    void getItemDetail(struct Item itm);
    /*functio to put deatils of an item*/
    void putItemDetail(struct Item itm);
 
    int main()
    {
        struct Item item={0,"Default",00.00f};  
        // item is the structure variable with default value initialising 
 
        printf("Enter detail of the Item :\n");
        getItemDetail(item);
        printf("\nEntered Item detail is :\n");
        putItemDetail(item);

	    getch();
        return 0;
    }
 
    /*function definition*/
    void getItemDetail(struct Item itm)
    {
        printf("Enter Item Id: ");
        scanf("%d",&itm.id);
        printf("Enter Item Name : ");
        fflush(stdin);
        gets(itm.name);
        printf("Enter Item Price : ");
        scanf("%f",&itm.price);
    }
 
    /*function definition*/
    void putItemDetail(struct Item itm)
    {
        printf("\nID: %d, Name : %s, Price : %.2f",itm.id, itm.name,itm.price);
    }
    
Output
    
    Enter detail of the Item :
    Enter Item Id: 111
    Enter Item Name : DOVE
    Enter Item Price : 57.75

    Entered Item detail is :
    ID: 0, Name : Default, Price : 0.00
    
Here, default values will print, because at the time of calling getItemDetail() & putItemDetail(), function creates a copy of Item variable into Itm and whatever changes made in Itm, will not effect to Item.

Consider the example with Call By Reference
    #include<string.h>
    #include<stdio.h>

    /* structure declaration*/
    struct Item
    {
        int id;
        char name[30];
        float price;
    };

    /*functio to get deatils of an item*/
    void getItemDetail(struct Item *itm);
    /*functio to put deatils of an item*/
    void putItemDetail(struct Item *itm);

    int main()
    {
	    struct Item item={0,"Default",00.00f};	
	    // item is the structure variable with default value initialising 

	    printf("Enter detail of the Item :\n");
	    getItemDetail(&item);
	    printf("\nEntered Item detail is :\n");
	    putItemDetail(&item);
	    return 0;
    }

    /*function definition*/
    void getItemDetail(struct Item *itm)
    {
	    printf("Enter Item Id: ");
	    scanf("%d",&itm->id);
	    printf("Enter Item Name : ");
	    fflush(stdin);
	    gets(itm->name);
	    printf("Enter Item Price : ");
	    scanf("%f",&itm->price);
    }

    /*function definition*/
    void putItemDetail(struct Item *itm)
    {
	    printf("\nID: %d, Name : %s, Price : %.2f",itm->id, itm->name,itm->price);
    }
    
Output
    
    Enter detail of the Item :
    Enter Item Id: 123
    Enter Item Name : DOVE
    Enter Item Price : 57.75

    Entered Item detail is :
    ID: 123, Name : DOVE, Price : 57.75
    
Here, actual input values print, because at the time of calling getItemDetail() & putItemDetail(), function sends the address of Item variable into Itm (which is a pointer type) and whatever changes made in Itm, will do effect to Item.

Structure with in Structure

You can also declare a structure with in the structure declaration; it is also known as nested structure declaration.

Syntax
    struct <structure-name>
    {	members;
        struct <structure-name>
        {
	        Members;
        };
    };
    


Consider the declaration of Nested Structure

1 : structure2 declaration inside
        struct student
        {
	        int		rollNo;
	        char	name;
	        float	perc;
	        struct	dateOfBirth
	        {
		        int dd;
		        int mm;
		        int yy;
	        }dob;
        };
    
2 : structure2 declaration outside of the structure
        struct dateOfBirth
        {
		        int dd;
		        int mm;
		        int yy;
        };
        struct student
        {
	        int	    rollNo;
	        char	name;
	        float	perc;
	        struct	dateOfBirth dob;
        };
    


Consider the example
        #include<string.h>
        #include<stdio.h>

        /* structure declaration*/
        struct dateOfBirth
        {
		        int dd;
		        int mm;
		        int yy;
        };
        struct student
        {
	        int		rollNo;
	        float	perc;
	        char	name[30];
	        struct	dateOfBirth dob;
        };

        int main()
        {
	        struct student std;
	        printf("Enter Roll No. :");
	        scanf("%d",&std.rollNo);

	        printf("Enter Name :");
	        fflush(stdin);
	        gets(std.name);

	        printf("Enter percentage :");
	        scanf("%f",&std.perc);

	        printf("Enter Date of birth (DD/MM/YYYY format):");
	        scanf("%d/%d/%d",&std.dob.dd,&std.dob.mm,&std.dob.yy);

	        printf("\nStudent's Entered Details :");
	        printf("\nRoll No : %d\nName : %s\nPercentage :%.2f\nDOB: %02d/%02d/%02d",std.rollNo,std.name,std.perc,std.dob.dd,std.dob.mm,std.dob.yy);
	        return 0;
        }
        
Output
        
        Output
        Enter Roll No. :101
        Enter Name :Mike
        Enter percentage :88
        Enter Date of birth (DD/MM/YYYY format):19/12/1992

        Student's Entered Details :
        Roll No : 101
        Name : Mike
        Percentage :88.00
        DOB: 19/12/1992
        


UNION

The concept of Union is similar to Structure. Declaration of Union, Declration of Union variable, Initiaizing of Union Members is same as structure except keyword union instead of keyword struct.
The one difference between structure and union is that “Union enables to store different type’s value on same memory location.” You define a Union with Multiple Union Members but only one memory space will be created based on the largest data type’s variable from the declared union members and it will shared with all data members.

Declaration
        union <union-name>
        {
            Union-Member1;
            Union-Member2;
            ...
        } <union-variables>;  
        

Consider the example
        #include<stdio.h>
        union sample
        {
	        char	a;
	        int 	b;
	        float	c;
	
        };

        int main()
        {
	        // initialising with union variable declaration
	        union sample s;
	        s.a='A';
	        s.b=200;
	        s.c=12.34f;

	        printf("\na=%c, b=%d, c=%f",s.a,s.b,s.c);

	        return 0;
        }
        
Output

        a=ñ, b=1095069860, c=12.340000
        
Here, value of c will print correct only. Because member a and b will be corrupted according to union rule. But you can use (print) just after the initializing of member.

Consider the example to access all members
        #include<stdio.h>

        union sample
        {
	        char	a;
	        int		b;
	        float	c;
	
        };

        int main()
        {
	        // initialising with union variable declaration
	        union sample s;
	        s.a='A';
	        printf("\na=%c",s.a);
	        s.b=200;
	        printf("\na=%d",s.b);
	        s.c=12.34f;
	        printf("\na=%f",s.c);

	        return 0;
        }
        
Output

        a=A
        a=200
        a=12.340000
        


Difference between structure & union

Structure Union
struct keyword is used to declare a structure. union keyword is used to declare a union.
Allocate memory space for each member. Allocate memory space for largest member.
All members can be initialized at once. Only first member can be initialized at once.
Individual member of the structure can be accessed at a time. Only one member of the union can be access at a time.
Self referential structure can be implemented. Self referential union cannot be implemented.






Copyright © 2024 www.includehelp.com. All rights reserved.