A structure is essentially a custom data type that consolidates logically connected elements into a singular entity. Accessing this singular entity enables us to utilize all the various data items it contains.
All data items are stored in adjacent memory locations. This allocation is not restricted to a single data type but can accommodate various types of data. Prior to utilization, it must be declared, similar to how a variable is declared before being used within a program.
Structure definition syntax:
struct_structure_name
{
data_type_variable_name;
data_type_variable_name;
........
data_type_variable_name;
};
Example:
Suppose we have to keep a record of an employee's information, such as identification number, full name, age, salary, job title, and various other attributes that fall under diverse data types.
struct Empl
{
int emp_id;
float salary;
char designation[20];
int depart_no;
int age_of_emp;
};
Memory space allocation:
Let's say we have saved an identifier. It is stored at a specific location, for instance, at address 8000, requiring 2 memory units due to its integer data type. Following the identifier, the next piece of information, the name, is situated right after the identifier at address 8002. This sequence continues for all the stored items, ensuring they are stored consecutively.
8000 -> emp_id (2 bytes)
8002 -> name[20] (20*1 = 20 bytes)
8022 -> salary (4 bytes)
8026 -> designation[50] (50*1 = 50 bytes)
8076 ->dept_no (2 bytes)
8078 -> age (2 bytes)
Example program:
//To show the memory allocation
#include<stdio.h>
struct student
{
int rollno;
int marks;
char name[10];
};
int main()
{
int size;
struct student s; //Declaring a structure variable
size = sizeof(s);
printf("\nSize of the Structure : %d", size);
return 0;
}
Output:
Size of the structure: 14
Point to understand:
Here,
Size of the structure 'S' is determined by adding the size of the 'roll', the size of the 'name', and the size of the 'mark' fields together.
= 2 + 10 + 2 = 14
Accessing the members of a structure:
We are unable to set up the structure within the declaration and we are not able to directly retrieve the elements by their names. Following the definition of the structure, it is necessary to instantiate a variable of that particular data type.
Now, we utilize this variable to retrieve the elements within the structure by employing the unique operator (.). An illustration is provided below;
struct Emp e1;
e1 is the structure variable now.
To access the data items in the structure:
- name
- salary
- emp_id
- address
- dept_no
Here is another example:
struct employee e1;
e1.id = 111;
e1.name = "Ravi"
e1.salary = 56,000
Another way:
struct employee e1 = {111,"Ravi",56,000};
Example programs:
//To store the details of a student
#include<stdio.h>
struct student1
{
int rollno;
char name[10];
int marks;
};
void main()
{
int size;
struct student1 s={110,"Sarika",568};
printf("Roll no : %d\n", s.roll);
printf("Name : %s\n", s.name);
printf("Marks : %d\n", s.marks);
}
Output:
Roll no : 110
Name : Sarika
Marks : 568
//2. Input from user:
#include <stdio.h>
struct stud
{
int roll;
char name[50];
float marks;
} s;
void main()
{
printf("Enter the name of student: ");
scanf("%s", s.name);
printf("Enter his/her roll number: ");
scanf("%d", &s.roll);
printf("Enter his/her marks: ");
scanf("%f", &s.marks);
printf("Displaying the Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %f\n", s.marks);
}
Output:
Enter the name of the student: Sagari
Enter his/her roll number: 6
Enter his/her marks: 780
Displaying the information:
Name: Sagari
Roll number: 6
Marks: 780
Assigning one structure to another:
We have the capability to assign an entire structure to another structure. By doing so, we enable the retrieval of members from one structure by utilizing the variable of the other structure, and the reverse is also true.
Let's consider e1 and e2 as the variables belonging to two structures, Emp1 and Emp2, respectively. If we assign the value of e2 to e1:
e1 = e2;
Now, each attribute of the Emp2 structure is allocated to the corresponding attributes of Emp1.
Array of structures:
It is employed to gather a substantial amount of identical data collectively. In this case, we assign an array as a struct variable instead of a regular variable. As a result, we are able to accommodate a greater amount of information.
Syntax:
struct_struct_name_array_name_value;
Implementation:
#include<stdio.h>
struct Employee
{
int Id;
int Age;
char Name[25];
long Salary;
};
void main()
{
int i;
struct Employee E[ 3 ];
for(i=0;i<3;i++)
{
printf("\nEnter detailsof the Employee",i+1);
printf("\n\tEnter Employee Id : ");
scanf("%d",&E[i].Id);
printf("\n\tEnter Employee Name : ");
scanf("%s",&E[i].Name);
printf("\n\tEnter Employee Age : ");
scanf("%d",&E[i].Age);
printf("\n\tEnter Employee Salary : ");
scanf("%ld",&E[i].Salary);
}
printf("\nDetails of Eloyees");
for(i=0;i<3;i++)
{
printf("\n%d\t%s\t%d\t%ld",E[i].Id,E[i].Name,E[i].Age,E[i].Salary);
}
}
Output:
Enter detailsof the Employee
Enter Employee Id : 1
Enter Employee Name : Ravi
Enter Employee Age : 21
Enter Employee Salary : 23000
Enter detailsof the Employee
Enter Employee Id : 2
Enter Employee Name : Rajesh
Enter Employee Age : 32
Enter Employee Salary : 67890
Enter detailsof the Employee
Enter Employee Id : 3
Enter Employee Name : Kiran
Enter Employee Age : 34
Enter Employee Salary : 23435
Details of Eloyees
1 Ravi 21 23000
2 Rajesh 32 67890
3 Kiran 34 23435
Structures within a structure:
We have the ability to designate a structure as a variable within another structure. This technique enables the establishment of a distinct container specifically for an essential element of the structure, allowing for the storage of more precise and lucid information.
Syntax:
struct struct_name;
struct_name
{
data_type variable_name;
struct struct_name
{
data_type variable_name;
........
}struct_variable;
} variable_name;
Example:
struct employee
{
int emp_id;
char name[20];
float salary;
int dept_no;
struct date
{
int day;
int month;
int year;
}doj;
}e1;
Here, a variable named doj was incorporated into the date structure, enhancing the clarity and providing detailed information about the specific day, month, and year.
To access these members,
The syntax for accessing the contents of one structure within another structure is ```
structstructurename
{
datatypevariable_name;
datatypevariable_name;
........
datatypevariable_name;
};
struct variable. nestedstructvariable. structmember;
Example:
In the above example:
e1.doj.day; -> for day in date
e1.doj.month; -> for month in date
e1.doj.year; -> for year in month
Full program example:
include <stdio.h>
struct Emp
{
int id;
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main
{
e1.id=101;
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id);
printf( "employee date of joining (dd-mm-yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
}
Output:
employee id : 101
employee date of joining (dd/mm/yyyy) : 10-11-2014
### UNION:
Similar to a structure, a union is a custom data type that combines logically associated variables into a singular entity.
Nearly all the characteristics and syntaxes remain consistent, with only a few variables differing.
Syntax:
union union_name
{
datatype variablename;
datatype variablename;
........
datatype variablename;
};
Example:
union Emp
{
char address[50];
int dept_no;
int age;
};
Memory allocation in a union:
In a data structure, the total memory allocated to it is essentially the combined memory allocation of all its components because they are arranged consecutively, each with its own memory allocation.
However, within a union, data elements are stacked on top of each other. Therefore, the overall memory needed to store a union corresponds to the memory needed to store its largest element.
Another key distinction to note is that within a structure, there is the ability to access multiple items simultaneously, whereas in a union, only a single item can be accessed at any given moment.
### Here is a table to differentiate all the factors between a structure and a union:
| Structures | Unions |
| --- | --- |
| The keyword "struct" is used to define a structure. | The keyword "union" is used to define a structure. |
| A unique memory location is given to every member of a structure | One single memory location is shared by all its members |
| Modifying the value of one item won't affect the other items or the structure at all. | Modifying one single data item affects other members of the union thus affecting the whole unit. |
| We initialize several members at once. | We can initialize only the first member of union. |
| The total size of the structure is the sum of the size of every data member | The total size of the union is the size of the largest data member |
| It is mainly used for storing various data types | It is mainly used for storing one of the many data types that are available. |
| It occupies space for each and every member written in inner parameters | It occupies space for a member having the highest size written in inner parameters |
| We can retrieve any member at any time | We can only access one member at a time in the union. |