为什么新的字符串上的strcat()在strcpy没问题的时候会在开头剔除未定义的字符?

j r*_*riv 0 c

例如

sprintf(pos,"%f ",cl.snap.ps.origin[0]); //don't start with strcat
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
Run Code Online (Sandbox Code Playgroud)

精细.

sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
Run Code Online (Sandbox Code Playgroud)

不好

Gre*_*ill 5

strcat()函数期望destination参数已包含正确的以null结尾的字符串.在你的情况下,它听起来像pos包含一些看起来像一个以null结尾的字符串的垃圾,但不是你所期望的.strcat()尽职尽责地追加到那个垃圾的尽头.

解决此问题的一种方法是pos在代码之前初始化:

pos[0] = '\0';
sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
Run Code Online (Sandbox Code Playgroud)