About Me

Structures and Unions

Structures provide a way of storing many different values in variables of different types under the same name. This makes it a more modular program, which is easier to modify because its design makes things more compact.
Structs are generally useful whenever a lot of data needs to be grouped together--for instance, they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct could be used that would hold all of the information about a single contact--name, address, phone number, and so forth.

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −

struct [structure tag] {
   member definition;
   member definition;
   ...
   member definition;
} [one or more structure variables];




The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book;



Initializing and using simple structures



#include <iostream>
#include <cstring>

using namespace std;

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

int main() {
   struct Books Book1;        // Declare Book1 of type Book
   struct Books Book2;        // Declare Book2 of type Book

   // book 1 specification
   strcpy( Book1.title, "Learn C++ Programming");
   strcpy( Book1.author, "Chand Miyan");
   strcpy( Book1.subject, "C++ Programming");
   Book1.book_id = 6495407;

   // book 2 specification
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Yakit Singha");
   strcpy( Book2.subject, "Telecom");
   Book2.book_id = 6495700;

   // Print Book1 info
   cout << "Book 1 title : " << Book1.title <<endl;
   cout << "Book 1 author : " << Book1.author <<endl;
   cout << "Book 1 subject : " << Book1.subject <<endl;
   cout << "Book 1 id : " << Book1.book_id <<endl;

   // Print Book2 info
   cout << "Book 2 title : " << Book2.title <<endl;
   cout << "Book 2 author : " << Book2.author <<endl;
   cout << "Book 2 subject : " << Book2.subject <<endl;
   cout << "Book 2 id : " << Book2.book_id <<endl;

   return 0;
}


When the above code is compiled and executed, it produces the following result −


Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700


----------------------------------------------------------------------------------------------------------------

C – Array of Structures

As you know, C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of structures is nothing but collection of structures. This is also called as structure array in C.

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:

This program is used to store and access “id, name and percentage” for 3 students. Structure array is used in this program to store and display records for many students. You can store “n” number of students record by declaring structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc.


#include <stdio.h>
#include <string.h>

struct student 
{
     int id;
     char name[30];
     float percentage;
};

int main() 
{
     int i;
     struct student record[3];

     // 1st student's record
     record[0].id=1;
     strcpy(record[0].name, "Raju");
     record[0].percentage = 86.5;

     // 2nd student's record         
     record[1].id=2;
     strcpy(record[1].name, "Surendren");
     record[1].percentage = 90.5;

     // 3rd student's record
     record[2].id=3;
     strcpy(record[2].name, "Thiyagu");
     record[2].percentage = 81.5;

     for(i=0; i<3; i++)
     {
         printf("     Records of STUDENT : %d \n", i+1);
         printf(" Id is: %d \n", record[i].id);
         printf(" Name is: %s \n", record[i].name);
         printf(" Percentage is: %f\n\n",record[i].percentage);
     }
     return 0;
}



OUTPUT:


Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000


---------------------------------------------------------------------------------------------

Structure and Function in C

Using function we can pass structure as function argument and we can also return structure from function.

Structure can be passed to function through its object therefore passing structure to function or passing structure object to function is same thing because structure object represents the structure. Like normal variable, structure variable(structure object) can be pass by value or by references / addresses.

Passing Structure by Value

In this approach, the structure object is passed as function argument to the definition of function, here object is reperesenting the members of structure with their values.

Example for passing structure object by value

#include<stdio.h>

       struct Employee
       {
              int Id;
              char Name[25];
              int Age;
              long Salary;
       };

       void Display(struct Employee);
       void main()
       {
              struct Employee Emp = {1,"Kumar",29,45000};

              Display(Emp);

       }

       void Display(struct Employee E)
       {
                    printf("\n\nEmployee Id : %d",E.Id);
                    printf("\nEmployee Name : %s",E.Name);
                    printf("\nEmployee Age : %d",E.Age);
                    printf("\nEmployee Salary : %ld",E.Salary);
       }

   Output :

              Employee Id : 1
              Employee Name : Kumar
              Employee Age : 29
              Employee Salary : 45000



Function Returning Structure


Structure is user-defined data type, like built-in data types structure can be return from function.

 #include<stdio.h>

       struct Employee
       {
              int Id;
              char Name[25];
              int Age;
              long Salary;
       };

       Employee Input();            //Statement   1

       void main()
       {
              struct Employee Emp;

              Emp = Input();

              printf("\n\nEmployee Id : %d",Emp.Id);
              printf("\nEmployee Name : %s",Emp.Name);
              printf("\nEmployee Age : %d",Emp.Age);
              printf("\nEmployee Salary : %ld",Emp.Salary);

       }

       Employee Input()
       {
              struct Employee E;

                    printf("\nEnter Employee Id : ");
                    scanf("%d",&E.Id);

                    printf("\nEnter Employee Name : ");
                    scanf("%s",&E.Name);

                    printf("\nEnter Employee Age : ");
                    scanf("%d",&E.Age);

                    printf("\nEnter Employee Salary : ");
                    scanf("%ld",&E.Salary);

              return E;             //Statement   2
       }


In the above example, statement 1 is declaring Input() with return type Employee. As we know structure is user-defined data type and structure name acts as our new user-defined data type, therefore we use structure name as function return type.
Input() have local variable E of Employee type. After getting values from user statement 2 returns E to the calling function and display the values.



----------------------------------------------------------------------------------------------------------


Unions

A union is like a structure in which all members are stored at the same address. Members of a union can only be accessed one at a time. The union data type was invented to prevent memory fragmentation. The union data type prevents fragmentation by creating a standard size for certain data. Just like with structures, the members of unions can be accessed with the . and -> operators.

 union jack {
  long number;
  char chbuf[4];
 } chunk;



As you know, C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of structures is nothing but collection of structures. This is also called as structure array in C.

______________________________________________________________________________


Difference between union and structure


Though unions are similar to structure in so many ways, the difference between them is crucial to understand.

The primary difference can be demonstrated by this example:

#include <stdio.h>
union unionJob
{
   //defining a union
   char name[32];
   float salary;
   int workerNo;
} uJob;

struct structJob
{
   char name[32];
   float salary;
   int workerNo;
} sJob;

int main()
{
   printf("size of union = %d", sizeof(uJob));
   printf("\nsize of structure = %d", sizeof(sJob));
   return 0;
}

Output

size of union = 32
size of structure = 40

More memory is allocated to structures than union as seen in the above example, there is a difference in memory allocation between union and structure.

The amount of memory required to store a structure variable is the sum of memory size of all members.





But, the memory required to store a union variable is the memory required for the largest element of an union.

Only one union member can be accessed at a time. In the case of structure, all of its members can be accessed at any time.

But, in the case of union, only one of its members can be accessed at a time and all other members will contain garbage values.


#include <stdio.h>
union job
{
   char name[32];
   float salary;
   int workerNo;
} job1;

int main()
{
   printf("Enter name:\n");
   scanf("%s", &job1.name);

   printf("Enter salary: \n");
   scanf("%f", &job1.salary);

   printf("Displaying\nName :%s\n", job1.name);
   printf("Salary: %.1f", job1.salary);

   return 0;
}


------------------------------------------------------- WAP Using Union------------------------

#include <stdio.h>
#include <string.h>

union student 
{
            char name[20];
            char subject[20];
            float percentage;
};

int main() 
{
    union student record1;
    union student record2;

    // assigning values to record1 union variable
       strcpy(record1.name, "Raju");
       strcpy(record1.subject, "Maths");
       record1.percentage = 86.50;

       printf("Union record1 values example\n");
       printf(" Name       : %s \n", record1.name);
       printf(" Subject    : %s \n", record1.subject);
       printf(" Percentage : %f \n\n", record1.percentage);

    // assigning values to record2 union variable
       printf("Union record2 values example\n");
       strcpy(record2.name, "Mani");
       printf(" Name       : %s \n", record2.name);

       strcpy(record2.subject, "Physics");
       printf(" Subject    : %s \n", record2.subject);

       record2.percentage = 99.50;
       printf(" Percentage : %f \n", record2.percentage);
       return 0;
}




OUTPUT:

Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000



Record1 union variable:

“Raju” is assigned to union member “record1.name” . The memory location name is “record1.name” and the value stored in this location is “Raju”.
Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is changed to “record1.subject” with the value “Maths” (Union can hold only one member at a time).
Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name is changed to “record1.percentage” with value “86.50”.
Like this, name and value of union member is replaced every time on the common storage space.
So, we can always access only one union member for which value is assigned at last. We can’t access other member values.
So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage” are empty.


Record2 union variable:

If we want to access all member values using union, we have to access the member before assigning values to other members as shown in record2 union variable in this program.
Each union members are accessed in record2 example immediately after assigning values to them.
If we don’t access them before assigning values to other member, member name and value will be over written by other member as all members are using same memory.
We can’t access all members in union at same time but structure can do that.

Post a Comment

0 Comments