我需要将具有给定尾随模式的另外两个字符串推回/追加到C中现有的char数组中。要实现这一点,我愿意如下使用“ sprintf”。
#include <stdio.h>
#include<string.h>
int main()
{
char my_str[1024]; // fixed length checked
char *s1 = "abcd", *s2 = "pqrs";
sprintf(my_str, "Hello World"); // begin part added
sprintf(my_str, "%s , push back '%s' and '%s'.", my_str, s1, s2); // adding more to end of "my_str" (with given trailling format)
/* here we always use 'my_str' as the first for the string format in sprintf - format starts with it */
return 0;
}
当我遵循此方法时,会收到“内存重叠”警告。这是一个严重的问题吗?(例如内存泄漏,错误的输出等)
调用时,不允许将相同的字符串用于输入和输出 sprintf()
因此,替换为:
sprintf(my_str, "%s , push back '%s' and '%s'.", my_str, s1, s2);
有了这个:
sprintf(my_str + strlen(my_str), " , push back '%s' and '%s'.", s1, s2);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句