10-C语言结构体-共用体-枚举

2018-09-16  本文已影响0人  低头看云

结构体是什么?

定义结构体

struct Person{
    char *name;
    int age;
    double height;
};

// 注意:结尾有分号

定义结构体变量

struct Person p; 
// Person 结构体名  
// p 结构体变量名
p.name = "cww";
p.age = 35;
p.height = 1.9;
printf("name = %s\n", p.name);
printf("age = %i\n", p.age);
printf("height = %lf\n", p.height);

结构体变量初始化的几种方式

定义结构体变量的几种方式

结构体类型作用域

结构体数组

struct Person {
    char *name;
    int age;
};
struct Person p[2];

- 先定义后初始化
```
struct Person {
    char *name;
    int age;
};
struct Person p[2];
p[0] = {"cww", 18};
p[1] = {"ppp", 20};
```

结构体内存分析

```
struct Person{
    int age; // 4
    char ch; // 1
    double score; // 8
};
struct Person p;
printf("sizeof = %i\n", sizeof(p)); // 16

```
- 调换顺序
```
struct Person{
    int age; // 4
    double score; // 8
    char ch; // 1
};
struct Person p;
printf("sizeof = %i\n", sizeof(p)); // 24

```

结构体指针

结构体嵌套定义

#include <stdio.h>

int main()
{
    // 定义一个日期的结构体
    struct Date{
        int year;
        int month;
        int day;
    };

    // 定义一个人的结构体
    struct Person{
        char *name;
        int age;
        // 嵌套定义
        struct Date birthday;
    };
    // 完全初始化
    struct Person p = {"cww", 18, {2020,02,20}};
    printf("name = %s\n", p.name);   // cww
    printf("year = %i\n", p.birthday.year);   // 2020
    printf("day = %i\n", p.birthday.day);    // 20


    return 0;
}

结构体和函数

#include <stdio.h>

int main()
{
    struct Person{
            char *name;
            int age;
        };
    struct Person p1 = {"cww", 18};
    struct Person p2;
    p2 = p1;
    p2.name = "ppp";   // 修改p2不会影响p1  是值拷贝
    printf("p1.name = %s\n", p1.name);  // cww 
    printf("p2.name = %s\n", p2.name);  // ppp
    return 0;
}

#include <stdio.h>
struct Person{
        char *name;
        int age;
    };
void test(struct Person p);
int main()
{

    struct Person p1 = {"cww", 18};

    printf("p1.name = %s\n", p1.name);  // cww
    test(p1);
    printf("p1.name = %s\n", p1.name);  // cww
    return 0;
}


void test(struct Person p){
    p.name = "hhh";
    printf("p1.name = %s\n", p.name); // hhh
}

共用体

union Test{
    int age;
    char ch;
};
union Test t;
#include <stdio.h>

int main()
{
    union Test {
        int age;
        char ch;
    };
    union Test t;
    printf("sizeof(t) = %i\n", sizeof(t));  //4

    t.age = 18;
    printf("t.age = %i\n", t.age);  // 18
    t.ch = 'a';
    printf("t.ch = %c\n", t.ch);  // a
    printf("t.age = %i\n", t.age);  // 97
    return 0;
}

枚举

enum Gender{
    male,
    female,
};
上一篇 下一篇

猜你喜欢

热点阅读