C Struct with typedef Guide

In C language, using the typedef keyword to define an alias for a structure can simplify the code and make it easier to read. Here is an example:

#include <stdio.h>

// 使用typedef定义一个结构体
typedef struct {
    int id;
    char name[20];
    float score;
} Student;

int main() {
    // 声明一个Student类型的变量
    Student student1;

    // 给结构体变量赋值
    student1.id = 1;
    strcpy(student1.name, "Alice");
    student1.score = 90.5;

    // 输出结构体变量的值
    printf("Student ID: %d\n", student1.id);
    printf("Student Name: %s\n", student1.name);
    printf("Student Score: %.1f\n", student1.score);

    return 0;
}

In the example above, we defined a structure named Student using typedef, and declared a variable of type Student named student1 in the main function. By using typedef, we can directly use Student to define structure variables without needing to write the struct keyword.

bannerAds