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:

struct Person { char name[50]; int age; char occupation[20]; };

Once you have defined a structure, you can create variables of that type. For example, the following code creates two variables of type Person:

struct Person person1, person2;

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:

person1.name = "Jimmy Carter";

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:

void print_person(struct Person person) { printf("Name: %s\n", person.name); printf("Age: %d\n", person.age); }

You can also use structures to create arrays of related data. For example, the following code creates an array of 10 Person variables:

struct Person people[10];

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:

printf("Name: %s\n", people[0].name); printf("Age: %d\n", people[0].age);
Full Source | C struct

The following code shows a complete example of how to use structures in C:

#include <stdio.h> struct Person { char name[50]; int age; char occupation[20]; }; void print_person(struct Person person) { printf("Name: %s\n", person.name); printf("Age: %d\n", person.age); printf("Occupation: %s\n", person.occupation); } int main() { struct Person person1, person2; person1.name = "Jimmy Carter"; person1.age = 30; person1.occupation = "Software Engineer"; person2.name = "William Carter"; person2.age = 25; person2.occupation = "Doctor"; print_person(person1); print_person(person2); return 0; }
//Output: Name: Jimmy Carter Age: 30 Occupation: Software Engineer Name: William Carter Age: 25 Occupation: Doctor

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.