嵌入式学习 c语言 构造数据类型 结构体

1.结构体基础语法

在C语言中,结构体(struct)用于将不同类型的数据组合成一个自定义数据类型。

struct 结构体名 {
    数据类型 成员1;
    数据类型 成员2;
    // 更多成员...
};

结构体示例代码

#include <stdio.h>

// 定义结构体
struct Student {
    int id;
    char name[50];
    float score;
};

int main() {
    // 声明结构体变量
    struct Student stu1;

    // 初始化结构体成员
    stu1.id = 101;
    strcpy(stu1.name, "Alice");
    stu1.score = 89.5;

    // 访问结构体成员
    printf("ID: %d\n", stu1.id);
    printf("Name: %s\n", stu1.name);
    printf("Score: %.2f\n", stu1.score);

    return 0;
}

2.结构体成员访问方式

方式语法示例说明
直接访问stu1.id通过结构体变量名访问成员
指针访问(箭头运算符)ptr->id通过结构体指针访问成员

3.结构体初始化方法

方法示例代码
逐成员初始化stu1.id = 101;
初始化列表struct Student stu1 = {101, "Alice", 89.5};
指定初始化器(C99)struct Student stu1 = {.id=101, .name="Alice"};

4.结构体嵌套

示例

结构体可以嵌套其他结构体作为成员:

struct Date {
    int day;
    int month;
    int year;
};

struct Employee {
    int empId;
    char name[50];
    struct Date hireDate; // 嵌套结构体
};

5.结构体的储存

内存对齐: 

  • 结构体成员必须存放在内存地址为自身类型长度整数倍的内存单元中
  • 结构体的大小必须为自身最大类型长度的整数倍
 struct student {
 char name[32];    //32
 char sex;         //1
 int age;          //4    凑整数倍,32+1(+1)+4
 int score          //4  
 };

 结果:44

6.结构体传参

在C语言中,结构体可以作为参数传递给函数。传递方式主要有两种:传值传址

1.传值方式

结构体直接作为参数传递时,会拷贝整个结构体的副本到函数中,函数内对结构体的修改不会影响原结构体。

struct Student {
    char name[50];
    int age;
};

void printStudent(struct Student s) {
    printf("Name: %s\nAge: %d\n", s.name, s.age);
}

int main() {
    struct Student stu = {"Alice", 20};
    printStudent(stu);  // 传值方式
    return 0;
}

2.传址方式

通过传递结构体指针,可以避免拷贝开销,且函数内对结构体的修改会影响原结构体。

void modifyStudent(struct Student *s) {
    strcpy(s->name, "Bob");
    s->age = 22;
}

int main() {
    struct Student stu = {"Alice", 20};
    modifyStudent(&stu);  // 传递结构体指针
    printf("Name: %s\nAge: %d\n", stu.name, stu.age);
    return 0;
}

结构体作为返回值传递

函数也可以返回结构体,但需要注意返回较大结构体时可能会有性能开销。

struct Student createStudent(char *name, int age) {
    struct Student s;
    strcpy(s.name, name);
    s.age = age;
    return s;
}

int main() {
    struct Student stu = createStudent("Charlie", 25);
    printf("Name: %s\nAge: %d\n", stu.name, stu.age);
    return 0;
}

7.结构体数组

数组元素个数必须是常量

数据类型 数组名[元素个数];

8.结构体数组初始化

struct student s[3] = {
    {"zhangsan", 'm', 19, 100},
    {"lisi", 'f', 18, 90},
    {"wanger", 'm', 19, 60},
 };
 struct student s[3] = {
    [1] = {
        .name = "zhangsan",
        .score = 90,
    },
 };

9.结构体数组传参

int fun(struct student *pstu, int len);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值