Structures
In C, a structure (or struct) is a user-defined data type that allows you to group different types of variables together. This is particularly useful when you want to represent more complex data types that involve multiple variables of different types. Structures help organize data logically and make the code more readable and maintainable.
Structures are ideal for bundling different data types together under one name, especially when representing real-world entities such as points, students, or complex numbers. For instance, instead of using separate variables for each property of a student (e.g., name, age, grade), you can group them into a single structure.
An example without structure:
int main(){
char student_firstName[20];
char student_lastName[20];
int student_age;
char student_gender;
double student_height;
char professor_firstName[20];
char professor_lastName[20];
int professor_age;
char professor_gender;
double professor_height;
student_firstName = "Ludwig"
student_lastName = "Boltzmann"
student_age = 26
...
professor_firstName = "Josef"
professor_lastName = "Stefan"
professor_age = 35
...
return 0;
}
wherease with structure we have:
struct info{
char firstName[20];
char lastName[20];
int age;
char gender;
double height;
};
int main(){
struct info student;
struct info professor;
student.firstName = "Ludwig"
student.lastName = "Boltzmann"
student.age = 26
...
professor.firstName = "Josef"
professor.lastName = "Stefan"
professor.age = 35
...
return 0;
}