跳转至

结构体

一、为什么需要结构体

为了表示一些负责的事物,而普通的基本数据类型无法满足实际要求

二、为什么叫结构体

把一些基本类型数据组合在一起形成的一个新的复合数据类型

三、如何定义结构体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 方式一
struct Student
{
    int age;
    float score;
    char sex;
};

// 方式二
struct Student
{
    int age;
    float score;
    char sex;
} st;
// 方式三
struct
{
    int age;
    float score;
    char sex;
} st;

四、结构体变量的使用

1. 赋值和初始化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
struct Student
{
    int age;
    float score;
    char sex;
};
int main(void)
{
    // 方式一
    // 定义的同时可以整体赋值
    struct Student st1 = {19, 66.6, 'F'}; // 初始化 定义的同时赋值
    // 方式二
    // 如果定义完后,只能单个赋初值
    struct Student st2;
    st2.age = 18;
    st2.score= 88;
    st2.sex = 'F';
    printf("%d %f %c\n", st1.age, st1.score, st1.sex);  // 19 66.599998 F
    printf("%d %f %c\n", st2.age, st2.score, st1.sex);  // 18 88.000000 F
    return 0;
}

2. 取出结构体变量中的成员

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
struct Student
{
    int age;
    float score;
    char sex;
};
int main(void)
{
    struct Student st = {19, 66.6, 'F'};
    // 方式一
    // 结构体变量.成员名
    printf("%d %f %c\n", st.age, st.score, st.sex);    // 19 66.599998 F
    // 方式二 更常用
    // 指针变量名->成员名
    struct Student *pst = &st;
    printf("%d %f %c\n", pst->age, pst->score, pst->sex);    // 19 66.599998 F
    // pst->age 在计算机内部会被转换为(*pst).age
    // 所以pst->age等价于(*pst.age),也等价于st.age
    // pst->age的含义:pst所指向的按个结构体变量中的age这个成员
    return 0;
}

3. 结构体变量和结构体变量指针作为函数参数传递

推荐使用结构体指针变量作为函数参数来传递

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 通过函数完成对结构变量的输入和输出
#include <stdio.h>
#include <string.h>

struct Student
{
    int age;
    char sex;
    char name[100];
};

void InputStudent(struct Student *pstu);
void OutputStudent(struct Student *stu);

int main(void)
{
    struct Student st;

    InputStudent(&st); // 对结构体变量输入 必须发送st的地址
    OutputStudent(&st); // 对结构体变量输出 可以发送st的地址,也可以发送st的内容
    return 0;
}


void InputStudent(struct Student *pstu)
{
    pstu->age = 10;
    strcpy(pstu->name, "张三");
    pstu->sex = 'F';
}

void OutputStudent(struct Student *pstu)
{
    printf("%d %c %s\n", pstu->age, pstu->sex, pstu->name);
}

//
// void OutputStudent(struct Student stu)
// {
//     printf("%d %c %s\n", stu.age, stu.sex, stu.name);
// }

4. 结构体变量的运算

结构体变量不能相加,不能相减,也不能相互乘除

可以相互赋值

1
2
3
4
5
6
7
8
9
struct Student
{
    int age;
    float score;
    char sex;
};

struct Student st1, st2;
st1 = st2;