C structs
Created By: chatGPT
In C programming, a struct (short for structure) is a user-defined data type that allows grouping of different data types together. This is particularly useful when you want to model complex data. A struct can contain members of various data types, including other structs.
struct Person {
char name[100];
int age;
float height;
};
To declare a variable of a struct type, you can do it in two ways: by directly defining the struct and then creating a variable, or by creating a struct variable after the struct definition. Here’s how you can use the struct defined above:
struct Person person1;
strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;
You can also initialize a struct variable at the time of declaration. This makes your code cleaner and more readable. Here's an example of how to declare and initialize a struct:
struct Person person2 = {"Bob", 25, 6.0};
Accessing the members of a struct is done using the dot operator. For instance, if you want to print the name and age of
person1
, you can do the following:printf("Name: %s, Age: %d\n", person1.name, person1.age);
To work with pointers to structs, you use the arrow operator (
->
). This is useful when passing structs to functions without copying them. Here’s how you can define a pointer to a struct and access its members:struct Person *ptr = &person1;
printf("Height: %.2f\n", ptr->height);
You can also create arrays of structs, which allows you to store a collection of similar items. This is particularly beneficial when dealing with multiple records in applications like databases or inventories. Here's an example of an array of
Person
structs:struct Person people[3];
people[0] = person1;
people[1] = person2;
strcpy(people[2].name, "Charlie");
people[2].age = 22;
people[2].height = 5.8;
Structs can also be used in functions, allowing you to pass complete records easily. Here's an example of a function that takes a struct as a parameter:
Using structs promotes better organization and improves the maintainability of your code. They encapsulate data and provide a clear structure for your program, making it more efficient and easier to understand.void printPerson(struct Person p) {
printf("Name: %s, Age: %d, Height: %.2f\n", p.name, p.age, p.height);
}
printPerson(person1);