当我编译并运行我的程序时,似乎一切正常,除了出现“运行时检查失败#2”错误,手头的任务都正常。这是我的主要任务,这是我第一次尝试使用任何cstring函数,所以我确信这是我出错的地方。基本上,我将两个字符串附加在一起,我几乎100%确定它与我的结果参数超出范围有关。只是不知道如何解决它。strncpy运行时检查失败#2错误C++
#include <iostream>
#include <cstring>
using namespace std;
void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength);
int main()
{
char a[] = "Woozle";
char b[] = "Heffalump";
char c[5];
char d[10];
char e[20];
concat(a, b, c, 5);
concat(a, b, d, 10);
concat(a, b, e, 20);
cout << c << "\n";
cout << d << "\n";
cout << e << "\n";
return 0;
}
void concat(const char a[ ], const char b[ ], char result[ ], int result_maxlength)
{
strncpy (result,a, result_maxlength);
strncat (result, b, result_maxlength);
result[result_maxlength-1] = '\0';
}
这和你以前的问题有何不同? http://stackoverflow.com/questions/12217528/strncat-strncpy-help-c?rq=1 –