Structures in C are a way to group together different variables of different data types. They are similar to classes in object-oriented programming languages, but do not have any methods associated with them.
To define a structure, we use the keyword "struct" followed by the name of the structure and a set of variables enclosed in curly braces. For example:
struct Person {
char name[20];
int age;
float height;
};
Once a structure is defined, we can create variables of that structure type. For example:
struct Person p1;
We can also initialize a structure variable when it is declared by specifying the values for each member in the order they were defined. For example:
struct Person p2 = {"John Doe", 25, 6.1};
We can access the members of a structure variable using the dot operator (.). For example:
p1.name = "Ranjeet Kumar";
p1.age = 30;
p1.height = 5.5;
printf("Name: %s\nAge: %d\nHeight: %f\n", p1.name, p1.age, p1.height);
We can also define pointers to structure variables, which can be useful for passing structures to functions or for dynamic memory allocation. For example:
struct Person *p3 = &p1;
printf("Name: %s\nAge: %d\nHeight: %f\n", p3->name, p3->age, p3->height);
Structures in C can be very useful for organizing data in a logical and meaningful way. They allow us to create complex data types that can be used throughout our code, making it more readable and maintainable.
In addition to this, structures can also be used as an element of an array. This way we can create an array of structures and can access the elements of the structure using the array index.
struct Person persons[5];
persons[0].name = "John Doe";
persons[0].age = 25;
persons[0].height = 6.1;
In conclusion, Structures in C are a powerful tool for organizing data, and are widely used in many types of applications. They allow us to create complex data types that can be used throughout our code, making it more readable and maintainable.