Structures and Union

Unlike the array, which stores the data in the variables of the same data type, Structures and Union are used for data storage in variables but of different data types. Suppose, you need to take the information of an Employee, the information which you want to collect from them is : Employee Name, DOB (Date of Birth), Salary.
As you can see, Employee Name will be having data type "char", DOB can also have data type "char" and Salary is stored in "integer" data type. For this, we can use structures.

Difference Between Structures & Union?

# Structures & Union are one and the same thing but the only difference is in the memory allocation in both. Structures assign memory to every variable which is declared, and Union only assigns the memory which the last variable in the list is declared to. 

Both Structures and Union have the same data type. Only in structure, you need to use the keyword "struct" and in Union, you need to use the keyword "union".

Let's see the syntax.

struct structureName;
{
 dataType nameOfVariable[size];
 dataType nameOfVariable[size];
 .....
 .....
}noOfObjects;

Here, noOfObjects means of many times people, you need to take the information of. Let's learn with the help of example. 

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

Explaination : We have created a student structure which is having name as a variable of data char and size of it is 20. Same way, we have variable marks of the data type integer and size of it is 20. After }, you have the number of times, you need to take the data. Here, student[1], so the value will be stored as student0, student1.

How to assign values to structure?

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

for(i=0;i<=1;i++)
{
 printf("Name = ");
 scanf("%s", student.name[i]);
 printf("Marks = ");
 scanf("%d", student.marks[i]);
}

How to print the structure? 

You can use the for Loop for it. 

for(i=0;i<=1;i++)
{
 printf("Name = %s", student.name[i]);
 printf("Marks = %d", student.marks[i]);
}
Previous
Next Post »
0 Comment