Structures in C are used to group different types of data under a single name, which allows for the organization of related data into a single unit. This is particularly useful when dealing with entities that have multiple attributes of different data types. For example, a Student entity might have:
• A name (string)
• A roll number (integer)
• Marks (float)
Using structures, you can group these attributes together, making it easier to manage and manipulate them as a single unit.
In C, a structure is a user-defined data type that can hold a collection of different data types. Each element within a structure is called a member. Structures allow you to create complex data models that can simulate classes or templates found in other programming languages.
#include <stdio.h>
#include <string.h>
// Define a structure for a Student
struct Student {
char name[50];
int rollNumber;
float marks;
};
int main() {
// Create a structure variable
struct Student student1;
// Assign values to the structure members
strcpy(student1.name, "John Doe");
student1.rollNumber = 12345;
student1.marks = 85.5;
// Access and print structure members
printf("Name: %s\\n", student1.name);
printf("Roll Number: %d\\n", student1.rollNumber);
printf("Marks: %.2f\\n", student1.marks);
return 0;
}
Name: John Doe
Roll Number: 12345
Marks: 85.50
There are two main approaches to declare structure variables:
You define the structure and declare variables of that structure type within the main() function or any other function.
int main() {
struct Student student1; // Declare a structure variable
// Use student1
return 0;
}
Flexible: you can declare as many variables as needed in different functions.
You can declare structure variables while defining the structure.
struct Student {
char name[50];
int rollNumber;
float marks;
} student1, student2; // Declare variables student1 and student2
int main() {
// Use student1 and student2
return 0;
}
Convenient for defining and initializing a fixed number of variables.
The dot operator is used to access the members of a structure variable.
struct Student student1;
student1.rollNumber = 12345;
printf("Roll Number: %d\n", student1.rollNumber);
The arrow operator is used to access the members of a structure through a pointer to that structure.
struct Student student1;
struct Student *ptr = &student1;
ptr->rollNumber = 12345;
printf("Roll Number: %d\n", ptr->rollNumber);
• ptr is a pointer to student1.
• ptr->rollNumber is used to access rollNumber through the pointer.
Structures in C are a powerful way to handle and organize related data of different types. They provide a clear and efficient method to model complex data and are widely used in various programming scenarios. Understanding how to declare, initialize, and access structure members is essential for effective programming in C.