What is Structure in C: Definition, Example, and Usage
structure is a user-defined data type that groups different variables under one name. It allows you to combine variables of different types into a single unit for easier management and organization.How It Works
A structure in C works like a container that holds different pieces of data together, even if they are of different types. Imagine a mailbox where you can keep letters, postcards, and small packages all in one place. Similarly, a structure groups variables like numbers, characters, or arrays under one name.
This helps organize related data as one unit. For example, if you want to store information about a person, you can keep their name, age, and height together in a structure instead of separate variables. You define the structure once, then create variables of that structure type to hold actual data.
Example
This example shows how to define a structure for a person and use it to store and print data.
#include <stdio.h> #include <string.h> // Define a structure named Person struct Person { char name[50]; int age; float height; }; int main() { // Create a variable of type Person struct Person person1; // Assign values strncpy(person1.name, "Alice", sizeof(person1.name) - 1); person1.name[sizeof(person1.name) - 1] = '\0'; person1.age = 30; person1.height = 5.6f; // Print the values printf("Name: %s\n", person1.name); printf("Age: %d\n", person1.age); printf("Height: %.1f feet\n", person1.height); return 0; }
When to Use
Use structures when you want to group related data of different types into one unit. This makes your code cleaner and easier to manage. For example:
- Storing information about a person, like name, age, and address.
- Representing a point in 2D or 3D space with x, y, and z coordinates.
- Managing records in a database, such as employee details or product information.
Structures help organize complex data logically and make it easier to pass multiple related values to functions.
Key Points
- A structure groups variables of different types under one name.
- It is defined using the
structkeyword. - Structures help organize and manage related data easily.
- You can create multiple variables of the same structure type.
- Structures are useful for representing real-world objects in code.