一、结构体的基本构造

数组是由一些类型相同的数据类型组成,而结构体则是由一些不同类型相同数据类型组成。

结构体组成:

struct 结构体名称{
    成员列表;
};//分号一定要写

注意:

1.成员是结构体的一个组成成分,一般是基本数据类型,也可以是数组、指针、结构体。

2.成员列表为:数据类型 变量名称

3.不同结构体的成员是相互独立的,互不影响,一个结构体变量的成员更改,不影响另外一个。

二、结构体变量的定义和初始化

1.结构体变量的定义

变量与类型是不同的概念,在定义结构体类型后,还需要定义结构体变量。结构体变量定义一共有三种方法。

  1. 先定义结构类型,在定义结构变量
struct dog{
    int year;
    char gender;
};
struct dog dog1;

b.定义结构类型的同时,定义结构体变量

struct dog{
    int year;
    char gender;
}dog1;

c.直接定义结构体变量

struct{
    int year;
    char gender;
}dog1;

如果直接定义结构体变量,则这个结构体只能使用一次

2.结构体的初始化

结构体变量在赋值的同时可对结构体中的变量同时赋值。

#include<stdio.h>
int main() {
    struct Dog {
        int year;
        char gender;
    };
    struct Dog dog1={4,'m'};
    ……
}

注意:1.如果结构体中含有多个变量,在同时赋值时,要按照顺序依次赋值,不能跳过某个变量。

2.不能在变量结构体时进行赋值

如:

struct Dog {
        int year=4;
        char gender=’m';
    };

三、结构体的引用

引用结构体变量成员的方式为

结构变量名.成员名

如:

#include<stdio.h>
int main() {
    struct Dog {
        int year;
        char gender;
    };
    struct Dog dog1={4,'m'};
    printf("year=%d,gender=%c", dog1.year, dog1.gender);
    return 0;
}

四、结构体与typedef的结合使用

typedef为C语言的关键字,作用为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int ,char)和自定义的数据类型(struct).

对于typedef的使用,可以让结构体使用更加方便

#include<stdio.h> 
typedef struct Dog {
        int year;
        char gender;
    }dog;
int main() {
    dog dog1={4,'m'};
    printf("year=%d,gender=%c", dog1.year, dog1.gender);
    return 0;
}

上面的代码相当于首先创建了一个代码

struct Dog {
        int year;
        char gender;
    };

然后给struct Dog 取了一个新的名字dog;在后面定义初始化时,直接使用dog dog1.