我已阅读帖子 sprintf format specifier replace by nothing ,以及其他相关的,但还没有看到具体解决这个问题。
直到今天,我还从未见过仅使用 2 个参数的 sprintf
。
我的系统用于 sprintf()
的原型(prototype)是:
int sprintf (char Target_String[], const char Format_String[], ...);
在处理一些遗留代码时,我遇到了这个:(为了说明而简化)
char toStr[30];
char fromStr[]={"this is the in string"};
sprintf(toStr, fromStr);
我对原型(prototype)的解释是,第二个参数应该由 const char[]
组成,并接受标准的 ansi C 格式说明符 such as these .
但是上面的例子似乎在字符串 fromStr
作为第二个参数时工作得很好。
这纯粹是通过未定义的行为起作用的吗?还是这种用法完全合法?
我在 Windows 7 上工作,使用 C99 编译器。
最佳答案
完全合法。可变参数是可选的。
在这种情况下,printf 用作 strcpy,但解析 % 说明符的 fmt 字符串。
我会写 sprintf(toStr,"%s",fromStr);
所以它不必解析那个长字符串。
关于c - sprintf() 是否需要格式说明符才能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35675407/