STRUCTURE AND UNION

Structure is a collection of variables of different types under a single name.

For example: You want to store some information about a person: his/her name, citizenship number and salary. You can easily create different variables name, citNo, salary to store these information separately.

However, in the future, you would want to store information about multiple persons. Now, you'd need to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single name Person, and use it for every person. Now, the code looks much cleaner, readable and efficient as well.

This collection of all related information under a single name Person is a structure.

Structure Definition in C

Keyword struct is used for creating a structure.

struct person
{
    char name[50] ;
    int citNo ;
    float salary;
} ;

This declaration above creates the derived data type struct person.

way of creating a structure variable is:

struct person
{
    char name [50] ;
    int citNo ;
    float salary ;
} person 1, person 2, person 3 [20] ;

In both cases, two variables person1, person2 and an array person3 having 20 elements of type struct person are created. 

Accessing members of a structure

There are two types of operators used for accessing members of a structure.

  1. Member operator(.)
  2. Structure pointer operator(->)

Example of structure

Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet. (Note: 12 inches = 1 foot)

#incldue < stdio.h >
struct Distance
       {
           int feet;
           float inch;
       } dist1, dist2, sum;

int main ( )
{
    printf ( " 1st distance \ n " ) ;

    // Input of feet for structure variable dist1
    printf ( " Enter feet : " ) ;
    scanf ( " % d " , & dist1.feet ) ;

    // Input of inch for structure variable dist1
    printf ( " Enter inch: " ) ;
    scanf ( " % f " , & dist1.inch ) ;

    printf ( " 2nd distance \ n " ) ;

    // Input of feet for structure variable dist2
    printf ( " Enter feet : " ) ;
    scanf ( " % d " , & dist2.feet ) ;

    // Input of feet for structure variable dist2
    printf ( " Enter inch : " ) ;
    scanf ( " % f " , & dist2.inch ) ;

    sum.feet = dist1.feet + dist2.feet;
    sum.inch = dist1.inch + dist2.inch;

    if ( sum.inch > 12 )
    {
         //If inch is greater than 12, changing it to feet.
         ++sum.feet;
         sum.inch = sum.inch - 12;
    }

    // printing sum of distance dist1 and dist2
    printf ( " Sum of distances = % d \ ' - %.1f \ "" , sum.feet , sum.inch ) ;
    return 0;
}

STRUCTRE AND FUNCTIONS

Passing structures to a function

There are mainly two ways to pass structures to a function:

  1. Passing by value
  2. Passing by reference

Passing structure by value

A structure variable can be passed to the function as an argument as a normal variable.

If structure is passed by value, changes made to the structure variable inside the function definition does not reflect in the originally passed structure variable.

C program to create a structure student, containing name and roll and display the information.

# include < stdio.h >
struct student
{
    char name[50];
    int roll;
};

void display ( struct student stu ) ;
// function prototype should be below to the structure declaration otherwise compiler shows error

int main ( )
{
    struct student stud ;
    printf ( " Enter student's name : " ) ;
    scanf ( " % s " , & stud.name ) ;
    printf ( " Enter roll number : " ) ;
    scanf ( " % d " , & stud.roll ) ;
    display (stud ) ;   // passing structure variable stud as argument
    return 0;
}
void display ( struct student stu ) {
                                                      printf ( " Output\nName: %s " , stu.name ) ;
                                                      printf ( " \nRoll: %d ", stu.roll ) ;
                                                }

Passing structure by reference

The memory address of a structure variable is passed to function while passing it by reference.

If structure is passed by reference, changes made to the structure variable inside function definition reflects in the originally passed structure variable.

C program to add two distances (feet-inch system) and display the result without the return statement.

#include < stdio.h >
struct distance
{
   
int feet;
   
float inch;
};

void add(struct distance d1,struct distance d2, struct distance *d3); 

int main ( )
{
    struct distance dist1, dist2, dist3 ;

    printf ( " First distance \ n " ) ;
    printf ( " Enter feet :  " ) ;
    scanf ( " % d " , & dist1.feet ) ;
    printf ( " Enter inch : " ) ;
    scanf ( " % f ", & dist1.inch ) ;

    printf ( " Second distance \ n " ) ;
    printf ( " Enter feet :  " ) ;
    scanf ( " % d " , & dist2.feet ) ;
    printf ( " Enter inch : " ) ;
    scanf ( " % f " , & dist2.inch ) ;

    add ( dist1, dist2, &dist3 ) ; 

    //passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference
    printf ( " \ n Sum of distances = % d \ ' - %.1f \ " ", dist3.feet , dist3.inch ) ;

    return 0 ;
}
void add ( struct distance d1, struct distance d2 struct distance *d3 )
{
              //Adding distances d1 and d2 and storing it in d3
             d3->feet = d1.feet + d2.feet;
             d3->inch = d1.inch + d2.inch;

             if ( d3->inch >= 12 )

                                    {   /* if inch is greater or equal to 12, converting it to feet. */
                                          d3->inch -= 12;
                                        ++d3->feet;
                                    }
}

STRUCTRE AND POINTERS

Structures can be created and accessed using pointers.

Accessing structure's member through pointer

A structure's member can be accesssed through pointer

  1. Referencing pointer to another address to access memory

1. Referencing pointer to another address to access the memory

Consider an example to access structure's member through pointer.

# include < stdio.h >
typedef struct person
{
   int age;
   float weight;
};

int main ( )
{
    struct person *personPtr,  person1 ;
    personPtr = &person1;            // Referencing pointer to memory address of person1

    printf ( " Enter integer : " ) ;
    scanf ( " % d ", & ( *personPtr ).age ) ;

    printf ( " Enter number : " ) ;
    scanf ( " % f " , &( *personPtr ).weight ) ;

    printf ( " Displaying : " ) ;
    printf ( " % d % f " , ( * personPtr ).age, ( *personPtr ).weight ) ;

    return 0;
}

 

UNIONS

Unions are quite similar to Structures in c. Like structures, unions are also derived types.

union car
{
  char name[50];
  int price;
};

Defining a union is as easy as replacing the keyword struct with the keyword union

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 ( " \ n size of structure = %d " ,  sizeof (sJob) ) ;
   return 0;
}

 

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 \ n Name : % s \ n ", job1.name ) ;
   printf ( " Salary : %.1f ", job1.salary ) ;

   return 0 ;
}