- 原型:
char* strncpy(char* string1, char* string2, int n)
- 说明:用字符串string2的前n个字符覆盖字符串string1的前n个字符,如果string1本来有数据,会被覆盖
- 返回值类型: 返回覆盖后字符串的指针,也就是string1的指针
int main()
{
char a[] = "123456789";
char b[] = "abcd";
char* p = strncpy(a, b, 2); //只复制了b中的两个字符
cout << a << endl;
cout << p << endl;
cout << sizeof(a) << endl;
return 0;
}
运行结果:
不要以为问题就结束了,没那么简单,看下面代码
int main()
{
char a[] = "123456789";
char b[] = "abcd";
char c[] = "efghijklm";
cout << "操作前:" << endl;
cout << "a: " << a << endl << "b: " << b << endl << "c: " << c << endl << endl;
cout << "复制b中两个字符到a " << endl;
char* t1 = strncpy(a, b, 2);
cout << "a: " << a << endl;
cout << "返回值: " << t1 << endl;
cout << "sizeof(a): " << sizeof(a) << endl;
cout << "strlen(a): " << strlen(a) << endl << endl;
cout << "复制c中全部字符到b" << endl;
cout << b << endl;
char* t2 = strncpy(b, c, strlen(c));
cout << "b: " << b << endl << "返回值: " << t2 << endl;
cout << "sizeof(b): " << sizeof(b) << endl;
cout << "strlen(b): " << strlen(b) << endl;
return 0;
}
运行结果:
当复制c中字符到b中时,结果超过了预期,b的长度变成了14,但是b数组总长度只申请了5,没有出现访问越界,至少没有报错,是怎么回事?
于是又有了下面的代码:
int main()
{
char b[] = "abcd";
char c[] = "efghijklm";
cout << "操作前:" << endl;
cout << "b: " << b << endl << "c: " << c << endl << endl;
cout << "复制c中全部字符到b" << endl;
cout << b << endl;
char* t2 = strncpy(b, c, strlen(c));
cout << "b: " << b << endl << "返回值: " << t2 << endl;
cout << "sizeof(b): " << sizeof(b) << endl;
cout << "strlen(b): " << strlen(b) << endl;
return 0;
}
运行结果:
- 我们看到输出了乱码,表明发生了越界
- 因为b中最多只能容纳5个字符,包括终结符,复制时,终结符被覆盖,输出则不知道结尾,出现了越界
- 至于没有提示错误,可能是编译器内部做了优化,本次测试用的是
codeblock