Structure and Union
Structure and Union
Suppose we need to store the details of an employee. It includes ID, name, age, salary, designation and
several other factors which belong to different data types.
struct Empl
int emp_id;
float salary;
char designation[20];
int depart_no;
int age_of_emp;
};
Let's assume we stored id . It is stores somewhere say in address 8000, it needs 2 memory units as it
belongs to int data type. Now, the next item, name is stored after the id at 8002. In the same way, all
the items are stores contiguously.
Example program:
#include<stdio.h>
struct student
{
int rollno;
int marks;
char name[10];
};
int main()
int size;
size = sizeof(s);
return 0;
Output:
Point to understand:
Here,
= 2 + 10 + 2 = 14
Now, we use this variable to access the items of the structure using the special operator
(.). Here is an example;
1. #include <stdio.h>
2. struct stud
3. {
4. int roll;
5. char name[50];
6. float marks;
7. } s;
8. void main()
9. {
10. printf("Enter the name of student: ");
11. scanf("%s", s.name);
12. printf("Enter his/her roll number: ");
13. scanf("%d", &s.roll);
14. printf("Enter his/her marks: ");
15. scanf("%f", &s.marks);
16. printf("Displaying the Information:\n");
17. printf("Name: ");
18. puts(s.name);
19. printf("Roll number: %d\n",s.roll);
20. printf("Marks: %f\n", s.marks);
21. }
Output: