问题描述
定义结构体变量
typedef struct test
{
uint8_t test_a;
uint8_t test_b;
uint8_t test_c;
uint8_t test_d;
}test_t;
在收到特定格式心跳字符串 line 后,使用sscanf 将其字符串内容部分赋值给该结构体变量 test
字符传如下所示:
uint8_t temp;
sscanf(line, "test_a:%d test_b:%d test_c:%d test_d:%d ", &test.test_a, &temp,&test.test_c, &test.test_d);
note::
在使用时,结构体内变量test_b 已赋值为1,之后想通过sscanf 将line中的test_a,test_c,test_d的内容赋值给结构体,而将line 中的test_b的内容舍弃,但是使用过后,发现test_b的内容由1变成了0,值被改变了,但这是不被预期的
问题查找原因
经过排查bug 找到sscanf 后网上寻找资料
在采用 %d获取内容时原型使用的是int *,是四个字节的,而我定义的uint8_t 只有一个字节,在赋值过程中应该发生了覆盖,导致值被不预期的更改
解决
于是将结构体的变量类型uint8_t -> int,经测试,问题得到解决