C语言之结构体浅谈

来源:互联网 发布:吕中 奚美娟 知乎 编辑:程序博客网 时间:2024/05/28 03:03

一、什么是结构体

对于数组中,每个元素都是相同的,如果我们想使每个元素不同的话,我们可以考虑使用结构体。
结构体可以由多种不同类型的数据类型组成的新的数据类型

二、结构体的定义
格式:
struct 结构体名 {
    数据类型 变量1;
    数据类型 变量2;
    数据类型 变量3;
    ... ...
}
例如:

struct Student {    int age;    char *name;};

三、结构体变量的定义
1、先定义结构体,再定义变量

struct Student {    int age;    char *name;};struct Student stu;
2、定义结构体的同时定义变量

struct Student {    int age;    char *name;} stu; 
3、直接定义结构体变量

struct {    int age;    char *name;} stu;
四、结构体初始化

1、声明变量的同时进行初始化

struct Student {    int age;    char *name;};struct Student stu = {22, "hello"};
2、先声明变量再逐一进行初始化

struct Student stu;stu.age = 22;stu.name = "hello";
3、定义结构体的同时进行变量定义和初始化

struct Student {    int age;    char *name;} stu = {22, "hello"};
4、非顺序初始化
struct Student stu = {.name = "hello", .age = 22};
5、注意:如果没有初始化结构体,所有变量会自动的有默认值


五、访问结构体
1、结构体变量是基本数据类型
int age = stu.age;
char *name = stu.name;

2、结构体变量时结构体

struct Date {    int year;    int month;    int day;};struct Student {    int age;    char *name;    struct Date birthday;};struct Student stu = {22, "hello", {1999, 10, 10}};int year = stu.birthday.year;int month = stu.birthday.month;int day = stu.birthday.day;

3、相同结构体类型变量间可以整体赋值
struct Student stu1 = {23, "hello"};
struct Student stu2 = stu1;     // 把结构体变量stu1的值对应的赋值给stu2,所以stu2 = {23, "hello"}

六、结构体数组

1、定义方式

// 方式一struct Student {    int age;    char *name;} stus[3];// 方式二struct Student {    int age;    char *name;};struct Student stu[3];// 方式三struct {    int age;    char *name;} stus[3];
2、初始化
和数组的初始化一样,可以参照数组笔记。
stus = {{12, "hello"}, {23, "world"}, {24, "welcome"}}

七、结构体指针

1、格式
struct 结构体名 *指针名;

2、访问结构体的方式增加了
之前访问结构体的方式是
结构体变量名.成员变量名
现在增加了
(*指针名).成员变量名
指针名->成员变量名
struct Student {    int age;    char *name;};struct Student stu = {23, "hello"};struct Student *p = &stu;printf("%d, %s\n", stu.age, stu.name);printf("%d, %s\n", (*p).age, (*p).name);printf("%d, %s\n", p->age, p->name);

八、结构体与函数
1、结构体作为函数参数
结构体实参会把成员变量值对应的赋值给函数结构体参数对应的变量值,改变函数结构体参数不会影响到实参。

struct Student {    int age;    char *name;};void test(struct Student s){    // 对结构体s的操作不会影响到stu    s.age = 10;    s.name = "world";}int main(){    struct Student stu = {23, "hello"};    test(stu);    printf("%d, %s\n", stu.age, stu.name);    return 0;}

输出:
23, hello

2、结构体指针作为函数参数

struct Student {    int age;    char *name;};void test(struct Student * s){    // 对结构体s的操作会影响到stu    s->age = 10;    s->name = "world";}int main(){    struct Student stu = {23, "hello"};    test(&stu);    printf("%d, %s\n", stu.age, stu.name);        return 0;}

输出:

10, world



0 0
原创粉丝点击