📜  C结构联合枚举1(1)

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

C结构联合枚举1

结构体、联合体和枚举是C语言中非常重要的三种数据类型。本文将主要介绍它们的基本概念、定义方法及其在程序中的应用。

结构体

结构体是用来描述一组相关数据的数据类型。结构体的定义方法是在一对大括号里面定义成员变量,可以使用.号来访问成员变量。

下面是定义一个学生结构体的示例:

struct student
{
    char name[20];
    int age;
    float score;
};

在程序中使用该结构体可以按照如下方式:

#include <stdio.h>

int main()
{
    struct student stu1 = {"tom", 18, 89.5};
    printf("name:%s, age:%d, score:%.1f\n", stu1.name, stu1.age, stu1.score);
    
    return 0;
}

输出结果:

name:tom, age:18, score:89.5
联合体

联合体是与结构体类似的一种数据类型,它可以存储不同类型的数据,但同一时间只能存储其中一种类型的数据。联合体的定义方法也是在一对大括号里面定义成员变量,不同的是使用union关键字来定义联合体。

下面是定义一个保存整数或浮点数的联合体的示例:

union number
{
  int x;
  float y;
};

在程序中使用该联合体可以按照如下方式:

#include <stdio.h>

int main()
{
    union number num;
    num.x = 10;
    printf("x=%d, y=%.1f\n", num.x, num.y);
    num.y = 3.14f;
    printf("x=%d, y=%.1f\n", num.x, num.y);
    
    return 0;
}

输出结果:

x=10, y=0.0
x=1078523331, y=3.1

可以发现在num.x=10的时候num.y的值为0,在num.y=3.14f的时候num.x的值变了,这是因为它们是共用内存的,存储的是相同的数据段。

枚举

枚举是一种特殊的数据类型,它用于定义一些有限的数据集合,集合中的每个数据都被赋予一个整数值,这个整数值被称为枚举常量。枚举的定义方法是使用enum关键字,成员之间使用,分隔。

下面是定义一些颜色枚举常量的示例:

enum color {red, blue, yellow, green};

在程序中使用该枚举可以按照如下方式:

#include <stdio.h>

int main()
{
    enum color c;
    c = red;
    printf("red=%d, blue=%d, yellow=%d, green=%d\n", red, blue, yellow, green);
    printf("c=%d\n", c);
    
    return 0;
}

输出结果:

red=0, blue=1, yellow=2, green=3
c=0

以上便是C语言中结构体、联合体和枚举的基本概念、定义方法及其应用的介绍。