C structures are user-defined data types that allow programmers to group related variables of different data types under a single name. They provide a way to organize and manage complex data efficiently.
To define a structure in C, use the struct
keyword followed by the structure name and a block containing member variables:
struct Person {
char name[50];
int age;
float height;
};
Once defined, you can declare variables of the structure type:
struct Person person1, person2;
Alternatively, you can combine the definition and declaration:
struct Person {
char name[50];
int age;
float height;
} person1, person2;
Use the dot (.) operator to access individual members of a structure:
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 1.75;
You can initialize a structure at declaration time:
struct Person person3 = {"Jane Smith", 25, 1.68};
Structures can be passed to functions as arguments or returned from functions. This allows for modular and organized code:
void printPerson(struct Person p) {
printf("Name: %s\nAge: %d\nHeight: %.2f\n", p.name, p.age, p.height);
}
// Usage
printPerson(person1);
Structures can contain other structures as members, allowing for more complex data organization. For more information on this topic, see C Nested Structures.
You can create pointers to structures, which is useful for dynamic memory allocation and efficient function parameter passing:
struct Person *personPtr = &person1;
printf("Name: %s\n", personPtr->name); // Use -> operator with pointers
Structures are widely used in C programming for various purposes:
By mastering C structures, you'll be able to write more organized and efficient code, especially when dealing with complex data relationships. For more advanced usage, consider exploring C Unions and C Typedef to further enhance your data structuring capabilities.