写代码也这么多年了,有些非常基础的东西却让我差点栽跟头;
有如下一种场景的需求代码:
char tmp; char input[6]; memset(input, 0, 6); while(*ptr != 0) // ptr是得到了某块全局内存的 { tmp = *ptr; ptr++; strcat(input, &tmp); }
看起来感觉没啥问题,编译通过,功能正常,额... ,开始是正常啦,多操作几个来回,机器就跑飞了;
刚开始根本没怀疑这里,最后找了找,发现是这里的问题,看到在这个最基本的函数上面栽跟头,感觉就是年纪大了!
C 库函数 char *strcat(char *dest, const char *src) 把 src 所指向的字符串追加到 dest 所指向的字符串的结尾。
这操作的是字符串啊,眼前黑。
所以得先格式化成字符串后再使用
C 库函数 int sprintf(char *str, const char *format, ...) 发送格式化输出到 str 所指向的字符串。 sprintf(&tmp, "%c", *ptr);// tmp = *ptr;