We can not use an array if we represent a collection of data items of different types using a single name.Fortunately, C supports a constructed data type known as structures, a mechanism for packing data of different types.
Unlike arrays,Structures must be defined first for their formats that may be used later to declare structure variable.Let us use an example to illustrate the process of structure definition and the creration of structure variable.Consider a college database consisting of Student_name,Student_rollno,student_address.We can define a structure to hold the informations as follow:-
1 2 3 4 5 6 |
struct student_data { char student_name[20]; int student_rollno; char student_address[50]; }; |
The keyword struct declares a structure to hold the details of three data fields.These fields are known as structure element or members.
Syntax of structure :-
1 2 3 4 5 6 7 8 |
struct structure_name { data_type member_1; data_type member_2; data_type member_3; -------- ---------------- -------- ---------------- }; |
After defining a structure format we can declare variable of that type.A structure variable declaration is same as declaration of variable of any other data type.A general form is:-
1 |
struct structure_name variable_name; |
For example:-
1 2 3 4 5 6 7 |
struct student_data { char student_name[20]; int student_rollno; char student_address[50]; }; struct student_data student1,student2; |
Accessing members of a structure
We can access the member of a structure in a number of ways.
Member operator (.)
The link between a structure element or member and variable is established using dot operator(.) A general form is:-
1 2 |
student1 <strong>.</strong> student_rollno student2 <strong>.</strong> student_rollno |
Structure pointer operator()
If we want to access a structure pointer member then we use Structure pointer operator.
C Code Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <stdio.h> struct student_data { char name[20]; int rollno; char address[50]; }; struct student_data student1; void main() { printf("Enter student name"); scanf("%s", student1.name); printf("\n Enter student roll number"); scanf("%d", &student1.rollno); printf("\n Enter student address"); scanf("%s", student1.address); printf("\n Name of student is "); puts(student1.name); printf("\n Roll number is %d\n",student1.rollno); printf("\n Address of student is "); puts(student1.address); } |