Structure and Union

Structure
Structure is the collection of variables of different types.
Structure is user defined data type available in C that allows combining data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
·         Title
·         Book ID
·         Book Price
Syntax:
Example:
struct structure_name
{
    data_type member1;
    data_type member2;
    .
    data_type memeber;
}struct_variable;
struct book
{
    char title[20];
    int book_id;
    float price;
}bk1,bk2;

In above example bk1, bk2 are the structure variable.
At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional It can be also declared inside main like
//inside main
struct book bk1,bk2;
There are two types of operators used for accessing members of a structure.
-Member operator (.)
-Structure pointer operator (->) (will be used with structure and pointers )
Any member of a structure can be accessed as:
structure_variable.member1
structure_variable.member2
For example
bk1.title, bk1.book_id, bk1.price
Example of Structure
#include <stdio.h>
#include <stdio.h>
struct book
{
    char title[20];
    int book_id;
    float price;
}bk1; //struct variable
void main()
{
    clrscr();
    printf("Insert book details\n");
    printf("Enter book name: ");
    scanf("%s",&bk1.title);  // input title of book
    printf("Enter book id: ");
    scanf("%d",&bk1.book_id);  // input id of book
    printf("Enter price");
    scanf("%f",&bk1.price);  // input price of book
    printf(“Book Detail”);
    printf(“\nTitle ID Price”);
    printf(“\n%s %d %f”, bk1.title, bk1.book_id, bk1.price);
    getch();
}

#include <stdio.h>
#include <stdio.h>
struct book
{
    char title[20];
    int book_id;
    float price;
};
 void main()
{
    struct book bk1; //struct variable
    clrscr();
    printf("Insert book details\n");
    printf("Enter book name: ");
    scanf("%s",&bk1.title);  //input title of book
    printf("Enter book id: ");
    scanf("%d",&bk1.book_id);  // input id of book
    printf("Enter price");
    scanf("%f",&bk1.price);  // input price of book
    printf(“Book Detail”);
    printf(“\nTitle ID Price”);
    printf(“\n%s %d %f”, bk1.title, bk1.book_id, bk1.price);
    getch();
}


How structure members are stored in memory?
Contiguous (adjacent) memory locations are used to store structure members in memory.
In example
struct book
{
    char title[20];
    int book_id;
    float price;
};
There are 3 members declared char, int and float, so 20 bytes of memory is occupied by char title[20] , int  book_id is assigned 2 bytes and float price is assigned 4 bytes. Each member of structure is assigned individual memory.
Typedef with Structure
We can also use typedef keyword to declare structure like
typedef struct book
{
    char title[50];
    int book_id;
    float price;
}book1;
Inside main:
book b1,b2
Here, typedef keyword is used in creating a type book(which is of type as struct complex). Then, two structure variables b1 and b2 are created by this book type.
Array of Structure
Array of structures is collection of structure variables. This is also called as structure array in C.
Structure is used to store the information of One particular object but if we need to store multiple objects then Array of Structure is used
For example
struct book
{
    char title[20];
    int book_id;
    float price;
}bk1[10]; //Array of structure

struct book
{
    char title[20];
    int book_id;
    float price;
};
Inside main:
Struct book bk1[10]; //Array of structure

In case if we use to store the information of 10 books then structure of array is used.
bk[0] store the information of first book bk[1] store the information of second book and so on.

Example:
#include <stdio.h>
#include<conio.h>
struct Book
{
      charname[20];
      int id;
      int price;
}bk[3];

void main()
{
    int i;
    clrscr();
    for(i=0;i<3;i++)
    {
            printf("\nEnter the Name of Book    : ");
            gets(bk[i].name);
            printf("\nEnter the Id of Pages : ");
            scanf("%d",bk[i].id);
            printf("\nEnter the Price of Book   : ");
            scanf("%f",bk[i].price);
    } 

    printf("\n--------- Book Details ------------ ");
   

    for(i=0;i<3;i++)
    {
            printf("\nName of Book    : %s",bk[i].name);
            printf("\nNumber of Pages : %d",bk[i].id);
            printf("\nPrice of Book   : %f",bk[i].price);
    }   
    getch();
}


Nested Structure: Nested Structure
Structures can be nested within other structures in C programming.
Structure written inside another structure is called as nesting of two structures. We can write one Structure inside another structure as member of another structure.
struct result
{
   int sub1;
   int sub2;
   int sub3;
};

struct student
   {
            char name[20];
            int no;
            struct result rt1; //variable of structure result inside structure student
}st1;

Structure members are accessed using dot operator.
result‘ structure is nested within ‘student’ Structure.
Members of the ‘result‘ can be accessed using ’student
rt1 & st1 are two structure variables
Explaination:
to access sub1: st1.rt1.sub1
to access sub2: st1.rt1.sub2
to access name: st1.name

Union
union is a special data type available in C that allows to store different data types in the same memory location.
You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
To define a union, you must use the union keyword in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program.
For example
Syntax:
Example:
union union_name
{
    data_type member1;
    data_type member2;
    .
    data_type memeber;
}union_variable;
union Data
{
   int i;
   float f;
   char str[20];
}d;

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.
To access any member of a union, we use the member access operator (.).
While accessing union, we can have access to single data member at a time. we can access single union member using following two Operators
  1. Using DOT (.) Operator (also known as ember access operator)
  2. Using ARROW(->) Operator  (with union and pointer)
The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type.
#include <stdio.h>
#include <string.h>

union Data {
   int i;
   float f;
   char str[20];
};

void main( )
{

   union Data d;        //union variable
   clrscr();

   data.i = 10;
   printf( "d.i : %d\n", d.i);

   data.f = 220.5;
   printf( "d.f : %f\n", d.f);

   strcpy( d.str, "C Programming");
   printf( "d.str : %s\n", d.str);

   getch();
}
Structure allocates storage space for all its members separately. Whereas, Union allocates one common storage space for all its members.
We can access only one member of union at a time. We can’t access all member values at the same time in union.
Many union variables can be created in a program and memory will be allocated for each union variable separately.
Difference between structure and union in C:

S.no
C Structure
C Union
1
Structure allocates storage space for all its members separately.
Union allocates one common storage space for all its members.
Union finds that which of its member needs high storage space over other members and allocates that much space
2
Structure occupies higher memory space.
Union occupies lower memory space over structure.
3
Structure allocates storage space for all its members separately
Union allocates one common storage space for all its members
4
We can access all members of structure at a time.
We can access only one member of union at a time.
5
Structure example:
struct student
{
int mark;
char name[10];
float avg;
};
Union example:
union student
{
int mark;
char name[10];
float avg;
};
 6
For above structure, memory allocation will be like below.
int mark – 2B
char name[10] – 10B
float avg – 4B
Total memory allocation = 2+10+4 = 16 Bytes
For above union, only 10 bytes of memory will be allocated since char data type will occupy maximum space of memory over other data types.
Total memory allocation = 10 Bytes




0 comments:

Post a Comment