Structure in c
Struct is keyword to declare structure
Structure definition
It is collection of dissimilar data element
Syntax
Struct structure_name
{ data type 1 var1;
Data type2 var2;
.
.
Data type n var n;
}structure_variable ;
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other data type.
Example:
struct student
{
int mark;
char name[10];
float average;
}S;
struct student
{
int mark;
char name[10];
float average;
}S;
Initializing structure using normal variable:
S = {100, “Mani”, 99.5};
Accessing structure members using normal variable:
S.mark;
S.name;
S.average;
S.mark;
S.name;
S.average;
Array of Structure
We can also declare an array of structure variables. in which each element of the array will represent a structure variable.
Example :
struct employee emp[5];
The below program defines an array
emp
of size 5. Each element of the array emp
is of type Employee
.#include<stdio.h>
Void main()
{
struct Employee
{
char ename[10];
int sal;
} emp[5];
int i, j;
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}// End of main function
Structure within structure
We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.
- Example:
struct Student { char name[30]; int age; /* here Address is a structure */ struct Address { char locality; char city; int pincode; }addr; };