📜  struct (1)

📅  最后修改于: 2023-12-03 15:20:21.976000             🧑  作者: Mango

Struct in C programming

Structs are a user-defined data type in C programming. They allow you to group together related data of different data types and store them under a single name. Structs are very useful when you need to work with complex data structures that require different data types.

Defining a Struct

In C, you define a struct using the struct keyword followed by the name you want to assign to the struct. Inside the curly braces, you declare the members of the struct.

struct Person {
    char name[50];
    int age;
    float height;
};

In this example, we have defined a struct named Person with three members; name, age and height.

Accessing Struct Members

You can access the members of a struct using the dot notation (.).

struct Person john;
strcpy(john.name, "John Doe");
john.age = 30;
john.height = 170.5;

In this example, we have defined a Person struct named john and assigned values to its members.

Initializing a Struct

You can initialize a struct using the {} initializer.

struct Person john = {"John Doe", 30, 170.5};
Passing a Struct to a Function

To pass a struct to a function, you can simply pass the struct variable name as an argument.

void printPerson(struct Person p) {
    printf("Name: %s\n", p.name);
    printf("Age: %d\n", p.age);
    printf("Height: %0.2f\n", p.height);
}

int main() {
    struct Person john = {"John Doe", 30, 170.5};
    printPerson(john);
    return 0;
}
Conclusion

Structs are a powerful tool in C programming that allow you to group related data of different data types and work with complex data structures. Use them wisely to make your code more efficient and cohesive.