我需要向后推/将具有给定尾随模式的另外两个字符串附加到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()
的输出和输入参数之一使用相同的字符串。
使用新的字符串作为输出。
#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;
}
调用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);