yas*_*han 1 c memory-management
我需要将另一对带有给定尾随模式的字符串推回/附加到 C 中的现有字符数组。为此,我愿意使用“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;
}
Run Code Online (Sandbox Code Playgroud)
当我遵循这种方法时,我收到“内存重叠”警告。这是一个严重的问题吗?(如内存泄漏、错误输出等)
调用时不允许对输入和输出使用相同的字符串 sprintf()
所以,替换这个:
sprintf(my_str, "%s , push back '%s' and '%s'.", my_str, s1, s2);
Run Code Online (Sandbox Code Playgroud)
有了这个:
sprintf(my_str + strlen(my_str), " , push back '%s' and '%s'.", s1, s2);
Run Code Online (Sandbox Code Playgroud)