Linux 拨号vps windows公众号手机端

C语言之结构体定义typedef和struct怎么使用

lewis 9年前 (2016-12-20) 阅读数 9 #程序编程
文章标签 c语言

在C语言中,使用typedef关键字来定义一个结构体的别名,可以简化代码,使代码更易读。下面是一个例子:

#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;
}

在上面的例子中,我们使用typedef定义了一个名为Student的结构体,并在main函数中声明了一个Student类型的变量student1。通过typedef,我们可以直接使用Student来定义结构体变量,而不必再写struct关键字。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门