作者filiaslayers (司马云)
看板C_and_CPP
标题[问题] hex to string跑回圈有问题
时间Mon Feb 18 10:43:06 2019
开发平台(Platform): (Ex: Win10, Linux, ...)
linux debian
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
gcc 6.3
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
no
问题(Question):
问题如下详述
喂入的资料(Input):
int s=5;
char a[7]={0};
char p[]="414243444546";
htos(a,p,s);
printf("%d,%s\n",s,a);
预期的正确结果(Expected Output):
5,ABCDE
错误结果(Wrong Output):
0,ABCDE
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
hex to string的程式码
void htos(char *dst,const char *src,int len)
{
for (;len>0 && src[0] && src[1] && sscanf(src, "%2X", dst++) ;len--,src += 2);
}
https://gcc.godbolt.org/z/RKlxwH
补充说明(Supplement):
试了几次,似乎是a的大小跟差值s值小於2就会这样
像是是s=4 a[6]也会
但s=4 a[7]就会是4,ABCD
看了半天看不出到底为什麽...
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 60.251.130.156
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1550457789.A.DDC.html
※ 编辑: filiaslayers (60.251.130.156), 02/18/2019 10:53:26
1F:→ Lipraxde: %2hhx 02/18 11:10
It works!看起来是sscanf造成的?但到底是为什麽啊orz?
※ 编辑: filiaslayers (60.251.130.156), 02/18/2019 11:13:17
2F:→ Lipraxde: -Wall,%x的目标是给uint的,s变数被排在a後面的话可能 02/18 11:18
3F:→ Lipraxde: 会不小心盖到 02/18 11:18
看懂了,非常感谢~
※ 编辑: filiaslayers (60.251.130.156), 02/18/2019 11:23:34