结构体
初始化
第一种先定义结构体类型,再定义结构体变量
struct student //结构体类型 或 结构体名
{
int num;
char name[20]; //结构体成员
char sex;
int age;
float score;
char addr[30];
};
struct student stu1,stu2; //结构体变量
第二种一起定义
struct data // 结构体类型 或结构体名
{
int day int month; //结构体成员
int year
}time1,time2; //结构体变量
为了访问结构的成员,我们使用成员访问运算符(.)。
引用形式:<结构体类型变量名> . <成员名>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct // 无标签名,匿名结构体
{
char name[20]; //姓名
int num; //学号
int age; //年龄
char group; // 所在小组
float score; // 成绩
}stu1; // 结构体变量
int main()
{
// 给结构体成员赋值
stu1 = { "Tom",12,18,'A',123.3f };
printf("%s的学号是%d,年龄是%d,在%c组,今年的成绩是%.1f\n", stu1.name, stu1.num, stu1.age, stu1.group, stu1.score);
return 0;
}
sccanf
使用sccanf解析数据
int sscanf(const char *str, const char *format, ...);
参数
- str: 要从中读取数据的源字符串。
- format: 格式控制字符串,指定了如何解析字符串中的数据。它的语法和
scanf
中的格式控制符相同(例如%d
、%s
、%f
等)。 - …: 用于存储读取结果的变量,传入的变量应该与格式字符串中的格式匹配。
- sscanf 函数返回成功解析的项数。如果没有成功解析任何数据,返回值为
0
;如果发生错误,返回值为EOF
。
#include <stdio.h>
int main() {
char str[] = "123 45.67 hello";
int i;
float f;
char word[20];
// 从字符串中读取数据
int count = sscanf(str, "%d %f %s", &i, &f, word);
// 输出解析的结果
printf("Parsed %d items\n", count);
printf("Integer: %d, Float: %.2f, String: %s\n", i, f, word);
return 0;
}
输出:获取了几个数据就输出多少
Parsed 3 items
Integer: 123, Float: 45.67, String: hello
strcmp
使用 strcmp
判断是否为特定的控制命令
int strcmp(const char *str1, const char *str2);
参数:
- str1: 第一个要比较的字符串。
- str2: 第二个要比较的字符串。
返回值:
- 如果 str1 等于 str2,返回
0
。 - 如果 str1 小于 str2(字典序上),返回一个负值。
- 如果 str1 大于 str2(字典序上),返回一个正值。
字典序比较:
strcmp
通过逐个字符比较两个字符串的 ASCII 值来判断大小关系。若在某个位置上字符不相同,strcmp
会返回该位置字符的差值。- 如果所有字符都相同,则返回
0
,表示两个字符串完全相等。
if(strcmp((const char*)usart_read_buffer, "#VH")==0)
printf("VH=%d\n", error[0]);
else if(strcmp((const char*)usart_read_buffer, "#VD")==0)
printf("VD=%d\n", error[1]);
strcmp((const char*)usart_read_buffer, "#VH")
:如果收到#VH
指令,则输出error[0]
的值。strcmp((const char*)usart_read_buffer, "#VD")
:如果收到#VD
指令,则输出error[1]
的值
qsort
qsort
是 C 标准库中提供的一个通用排序函数,用于对任意类型的数组进行排序。
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
参数说明:
base
:- 指向要排序的数组的起始地址。
- 类型为
void *
,表示可以传入任意类型的数组。
nitems
:- 数组中的元素个数。
size
:- 每个数组元素的大小(单位:字节)。
- 使用
sizeof(type)
获取元素大小。
compar
:- 指向比较函数的函数指针,用于定义排序规则。
- 该函数需要两个参数(指向数组元素的指针),并返回:
- 负值:第一个元素小于第二个元素。
- 正值:第一个元素大于第二个元素。
- 零:两个元素相等。
使用步骤
- 定义比较函数:
- 根据要排序的数组元素类型,定义一个比较函数。
- 调用
qsort
:- 传入数组地址、元素数量、每个元素的大小和比较函数。
示例代码
#include <stdio.h>
#include <stdlib.h>
// 比较函数:升序排序
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int arr[] = {5, 2, 9, 1, 6};
int size = sizeof(arr) / sizeof(arr[0]);
// 使用 qsort 排序数组
qsort(arr, size, sizeof(int), compare);
// 打印排序结果
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}