云计算百科
云计算领域专业知识百科平台

嵌入式学习 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);

赞(0)
未经允许不得转载:网硕互联帮助中心 » 嵌入式学习 c语言 构造数据类型 结构体
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!