You are on page 1of 4

Some other Example of structure:

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;

};

Memory space allocation:

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.

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 Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)

= 2 + 10 + 2 = 14

Accessing the members of a structure:


We cannot initialize the structure in the definition and we cannot just access the
members by using the names. After defining the structure, we need to define a variable
of that structure data type.

Now, we use this variable to access the items of the structure using the special operator
(.). Here is an example;

1. struct Emp e1;


e1 is the structure variable now.

To access the data items in the structure:

Input from user:

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:

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

You might also like