奇怪的编译警告提示,运行时奇怪错误

lc19890326 2007-11-27 05:01:25
代码如下
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
const char *p1="love";
const char *p2="forever";
size_t size_arr=strlen(p1)+strlen(p2);
char *result_str=new char[size_arr+1];
strcpy(result_str,p1);
strcat(result_str,p2);
cout<<*result_str<<endl;
delete [] result_str;
return 0;
}
应该没什么错误吧
然后编译时的提示就是
1>------ 已启动生成: 项目: test, 配置: Debug Win32 ------
1>正在编译...
1>test.cpp
1>c:\documents and settings\lican\my documents\visual studio 2005\projects\test\test.cpp\test.cpp(10) : warning C4996: “strcpy”被声明为否决的
1> e:\vs2005\vc\include\string.h(73) : 参见“strcpy”的声明
1> 消息:“This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.”
1>c:\documents and settings\lican\my documents\visual studio 2005\projects\test\test.cpp\test.cpp(11) : warning C4996: “strcat”被声明为否决的
1> e:\vs2005\vc\include\string.h(78) : 参见“strcat”的声明
1> 消息:“This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.”
1>正在编译资源清单...
1>正在链接...
1>正在嵌入清单...
1>生成日志保存在“file://c:\Documents and Settings\LiCan\My Documents\Visual Studio 2005\Projects\test\test\Debug\BuildLog.htm”
1>test - 0 个错误,2 个警告
========== 生成: 1 已成功, 0 已失败, 0 最新, 0 已跳过 ==========
运行的时候只出现一个l字符,显然不符合预期
请高手解释是怎么回事
...全文
98 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
blueiris 2007-11-28
  • 打赏
  • 举报
回复
乍一看还真没注意 多个* hoho
xiaoQ008 2007-11-27
  • 打赏
  • 举报
回复
把result前面的*去掉
我的编译器是DEV C++
没错!
LHQokok 2007-11-27
  • 打赏
  • 举报
回复
result_str指向字符串的首地址,*result_str只是首字母l,当然得不到你要的结果了!
我做的程序,你参考一下
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int size_arr,i;
const char *p1="love";
const char *p2="forever";
size_arr=strlen(p1)+strlen(p2);
char *result_str=new char[size_arr+1];
strcpy(result_str,p1);
strcat(result_str,p2);
for(i=0;result_str[i]!='\0';i++)
cout <<result_str[i];
cout<<endl;
delete [] result_str;
return 0;
}
lc19890326 2007-11-27
  • 打赏
  • 举报
回复
是在VS2005下编译的
我也知道C++里面不建议用C-style数组,但是这个是C++primer里面的题目啊
我想知道原理
谢谢解答
hai040 2007-11-27
  • 打赏
  • 举报
回复
cout去掉*
vs2005?应该是不建议用这两个函数

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧