In this tutorial you will learn about the C Structures and its application with practical example.
In C Programing Language we can use arrays when we want to hold multiple elements of the homogeneous data type in a single variable, but what if we want to hold heterogeneous data type elements, using the c structures you can wrap one or more variables that may be in different data types into one.
Syntax:
1 |
struct struct_name{ structure_member }; |
To define a structure, you use the struct keyword followed by the structure name. The variables which are declared inside the structure are called ‘members of structure’.
Example:
1 2 3 4 5 6 |
struct student { int id; char name[20]; float percentage; }; |
The student structure contains id as a positive integer, name as a string, percentage code as afloat.
Declaring structure
The above example only defines a student structure without creating any structure variable. To declare a structure variable, you can do it in two ways:
Declaring structure with variables together:
1 2 3 4 |
struct struct_name { structure_member; ... } instance_1,instance_2 instance_n; |
Declaring the C structures variable after you define the structure:
1 |
struct struct_name instance_1,instance_2 instance_n; |
Note:– When declaring structure following points need to be kept in mind –
- The structure is always terminated with semicolons (;).
- Structure name as struct_name can be later used to declare c structures variables of its type in a program.
Accessing Structure Members
Member operator ‘.’ is used to accessing the individual structure members. It is also known as ‘dot operator’ or ‘period operator’.
Syntax:
1 |
structure_var.member; |
Example Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> #include <conio.h> struct student { char name[20]; char addr[100]; } student; void main() { clrscr(); printf("\n Enter Student Name : "); gets(student.name); printf("\n Enter percentage: "); gets(student.addr); printf("\n\n Student Name : %s",student.name); printf("\n\n Address : %s",student.addr); getch(); } |