脸上为什么长螨虫:strncpy函数为什么不按最大值复制?

来源:百度文库 编辑:神马品牌网 时间:2024/05/07 09:31:44
strncpy函数有一个是MaxLength.书上说这个函数可以把到第一个空字符为止的内容或指定的最大数目的字符复制到目标缓冲区.可是我在演示时确出现了一个奇怪的现象.请看下面的一个小程序:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char string1[]="no man is an island";
char string2[33];
strncpy(string2,string1,8);
cout<<string2<<endl;
return 0;
}
这个程序应该输出
no man i
对吧,可是实际的输出结果却是
no man i烫烫烫烫烫烫烫烫烫烫烫烫烫烫s an island
我不知道这是为什么,请高手指教!

strncpy 是不复制最后的 '\0' 结束符的,所以是不安全的,你复制完以后需要手工添加字符串的结束符才行。

------ 已启动全部重新生成: 项目: temp8, 配置: Debug Win32 ------
正在删除项目“temp8”(配置“Debug|Win32”)的中间文件和输出文件
正在编译...
001.cpp
g:\workdir\simplycpp\temp8\001.cpp(8) : warning C4996: “strncpy”被声明为否决的
d:\program files\microsoft visual studio 8\vc\include\string.h(156) : 参见“strncpy”的声明
消息:“This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.”
正在编译资源清单...
正在链接...
正在嵌入清单...
生成日志保存在“file://g:\WorkDir\SimplyCpp\temp8\Debug\BuildLog.htm”
temp8 - 0 个错误,1 个警告
========== 全部重新生成: 1 已成功, 0 已失败, 0 已跳过 ==========

将strncpy(string2,string1,8)改为strncpy_s(string2,string1,8)即可。
当然,#include <string.h>这句是没用的。可以删掉了。