C struct (Structures)
A structure in C is a user-defined data type that allows you to group together related data of different types. This can be useful for storing information about a specific entity, such as a student, employee, or product.
C struct
To define a structure, you use the struct keyword followed by the name of the structure and a list of its members. Each member is a variable of a specific data type. For example, the following code defines a structure called Person that has three members: name, age, and occupation:
Once you have defined a structure, you can create variables of that type. For example, the following code creates two variables of type Person:
To access the members of a structure, you use the dot operator (.). For example, the following code assigns the value "Jimmy Carter" to the name member of the person1 variable:
You can also use the dot operator to access the members of a structure that is passed as an argument to a function. For example, the following function prints the name and age of a person:
You can also use structures to create arrays of related data. For example, the following code creates an array of 10 Person variables:
To access the members of an element in the people array, you use the same syntax as you would to access the members of a single structure variable. For example, the following code prints the name and age of the first person in the people array:
The following code shows a complete example of how to use structures in C:
Conclusion
A structure is a composite data type that allows you to group variables of different data types together under a single name. It is used to create custom data types for organizing and managing related information efficiently, making it a fundamental tool for structuring and representing complex data in C programs.