Structures in C
A structure is a user-defined data type that groups variables of different data types under a single name. Each variable in a structure is called a member.
---
Defining a Structure
struct Student {
int rollNo;
char name[50];
float marks;
};
---
Declaring Structure Variables
struct Student s1; /* single variable */
struct Student s1, s2, s3; /* multiple variables */
struct Student s1 = {101, "Alice", 92.5}; /* with initialisation */
---
Accessing Members
Use the dot operator (.) to access structure members.
struct Student s1;
s1.rollNo = 101;
strcpy(s1.name, "Alice");
s1.marks = 92.5;
printf("Roll: %d, Name: %s, Marks: %.1f\n",
s1.rollNo, s1.name, s1.marks);
---
Array of Structures
struct Student class[30];
for (int i = 0; i < 30; i++) {
scanf("%d %s %f", &class[i].rollNo, class[i].name, &class[i].marks);
}
---
Structure and Functions
void display(struct Student s) {
printf("Roll: %d, Name: %s\n", s.rollNo, s.name);
}
int main() {
struct Student s1 = {101, "Bob", 88.0};
display(s1);
return 0;
}
---
Pointer to Structure
Use the arrow operator (->) with a pointer to a structure.
struct Student *ptr = &s1;
ptr->rollNo = 102;
printf("%s\n", ptr->name);
---
Nested Structures
struct Date {
int day, month, year;
};
struct Employee {
int id;
char name[50];
struct Date dob; /* nested structure */
};
struct Employee e1;
e1.dob.day = 15;
e1.dob.month = 8;
e1.dob.year = 1995;
---
sizeof a Structure
printf("%zu\n", sizeof(struct Student));
/* may be larger than sum of members due to padding */