如何使用 sprintf 在 C 中推回另一个字符串



我需要将另外几个具有给定尾随模式的字符串推送/附加到 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);

警告是因为不允许对sprintf()的输出和其中一个输入参数使用相同的字符串。规范说:

如果在重叠的对象之间进行复制,则行为是未定义的。

对输出使用新字符串。

#include <stdio.h>
#include<string.h>
int main()
{
char my_str[1024], my_str2[1024]; // fixed length checked
char *s1 = "abcd", *s2 = "pqrs";
sprintf(my_str, "Hello World"); // begin part added
sprintf(my_str2, "%s , push back '%s' and '%s'.", my_str, s1, s2); // adding more to end of "my_str" (with given trailling format)
return 0;
}

相关内容

最新更新