为什么sscanf会改变ph的值,太离奇了!
一个简单的C程序,在winodws和linux上都测试过了。发现结果非常离奇:sscanf改变了ph的值,到底是为什么呢?
#include <stdio.h>int main(){ int i = 0; char ph[] = "015865478569"; unsigned char bcd[6]; printf("1. ph = [%s]\n", ph); sscanf(ph, "%02x%02x%02x%02x%02x%02x", &bcd[0], &bcd[1], &bcd[2], &bcd[3], &bcd[4], &bcd[5]); //sscanf(ph, "%2x%2x%2x%2x%2x%2x", &bcd[0], &bcd[1], &bcd[2], &bcd[3], &bcd[4], &bcd[5]); printf("2. ph = [%s]\n", ph); // ?为什么ph为空了?? for(i = 0; i < 6; i++) printf("%02x ", bcd[i]); puts("\n"); return 0;}
#include <stdio.h>int main(){ int i = 0; char ph2[] = "015865478569"; char ph[] = "015865478569"; char ph1[] = "015865478569"; unsigned char bcd[6]; printf("1. ph = [%s]\n", ph); //sscanf(ph, "%02x%02x", &bcd[0], &bcd[1]); sscanf(ph, "%02x%02x%02x%02x%02x%02x", &bcd[0], &bcd[1], &bcd[2], &bcd[3], &bcd[4], &bcd[5]); //sscanf(ph, "%2x%2x%2x%2x%2x%2x", &bcd[0], &bcd[1], &bcd[2], &bcd[3], &bcd[4], &bcd[5]); printf("2. ph = [%s]\n", ph); // ?为什么ph为空了?? for(i = 0; i < 6; i++) printf("%02x ", bcd[i]); puts("\n"); return 0;}
[解决办法]
不会吧 我运行了一下,
结果输出啊 !!
1. ph = [015865478569]
2. ph = [015865478569]
01 58 65 47 85 69
[解决办法]
自己转换,每半字节存一个,只能0~F