Structure

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:-

	
	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 :-

	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:-

struct structure_name variable_name;

For example:-

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:-

variable_name . member_name

For example:-

	student1 . student_rollno
	student2 . student_rollno

Structure pointer operator()

If we want to access a structure pointer member then we use Structure pointer operator.

variable_name pointer_member_name

For example:-

student1 ptr_name
 

C Code Example

#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);
}