Structures in C
In C programming, "structure" refers to a user-defined composite data type that allows you to group variables of different types under a single name. Structures are used to represent a record, such as a student record or a complex data entity.
Definition of a structure
In C, a structure is defined using the 'struct' keyword followed by a name (identifier) for the structure, and inside curly braces '{}'' you define one or more members (variables) of various data types.
struct student {
  int id;
  char name[50];
  float percentage;
};
Declaring Structure Variables
After defining a structure, you can declare variables of that structure type :
struct student s1, s2;
Accessing Structure Members
You can access the members of a structure variable using the dot '.' operator :
s1.id = 1;
strcpy(s1.name, "John Doe");
s1.percentage = 85.5;
Initializing structure variables
You can initialize structure variables during declaration :
struct student s1 = {1, "John Doe", 85.5};
Nested structure
struct address {
char city[50];
char state[50];
};
struct employee {
int emp_id;
char emp_name[50];
struct address emp_address;
};
Examples
#include<stdio.h>
struct Student
{
char Name[50];
int Roll;
float Marks;
};
main()
{
struct Student s;
printf("Enter Name, Roll and Marks :");
scanf("%s\t%d\t%f", &s.Name, &s.Roll, &s.Marks);
printf("Name=%s\t Roll=%d\t Marks=%f", s.Name, s.Roll, s.Marks);
}
Ouput :
Enter Name, Roll and Marks :Rokeiya   25   90
Name=Rokeiya   Roll=25   Marks=90.000000
#include<stdio.h>
struct Distance
{
int Ft;
float Inch;
}d1,d2,s;
main()
{
printf("Enter the 1st value in feet and inch:\n");
scanf("%d %f", &d1.Ft, &d1.Inch);
printf("Enter the 2nd value in feet and inch:\n");
scanf("%d %f", &d2.Ft, &d2.Inch);
s.Ft=d1.Ft+d2.Ft;
s.Inch=d1.Inch+d2.Inch;
if(s.Inch>12)
{
s.Inch=s.Inch-12;
s.Ft++;
}
printf("Sum of Distance is:\n%d'%f", s.Ft, s.Inch);
}
Ouput :
Enter the 1st value in feet and inch: 5 9
Enter the 2nd value in feet and inch: 5 4
Sum of Distance is: 11'1.000000
#include<stdio.h>
struct Result
{
char Name[50];
int Mark;
};
main()
{
struct Result R[4];
struct Result p;
int i;
printf("Enter the name :");
scanf("%s", &p.Name);
for(i=0; i<4; i++)
{
printf("Enter Marks:");
scanf("%d", &R[i].Mark);
}
printf("%s", &p.Name);
printf("\nThe student's Result is:\n");
for(i=0; i<4; i++)
{
printf("%d\t", R[i].Mark);
}
}
Ouput :
Enter the name :Rokeiya
Enter Marks:90
Enter Marks:95
Enter Marks:85
Enter Marks:80
Rokeiya
The student's Result is: 90 95 85 80
conclusion
Understanding structures is fundamental in C programming for managing and organizing data effectively. They provide a way to represent real-world entities or abstract data structures in a manner that is both intuitive and efficient. Mastering structures is essential for building complex programs and data structures in C.