char *end =...;*(end - 1) = '\0';这样是对还是错?

江南烟雨梦 2009-12-03 10:52:12
程序1:

#include <stdio.h>
#include <fstream>

using namespace std;
int main()
{
char *read_buf = NULL;
ifstream fins("1.txt", ifstream::in);//“1.txt”的内容:“Hello world!<!----//----->Hello china!”

if (!fins.good())
{
fins.close();
return 0;
}

fins.seekg(0, ios::end);
int length = fins.tellg();
fins.seekg(0, ios::beg);

read_buf = new char[length + 1];
memset(read_buf, 0, length + 1);

if (read_buf)
fins.read (read_buf, length);
else
return 0;

char *end = strstr(read_buf, "<!");
*(end - 1) = '\0';
//*(end + 1) = '\0';//这样做是正确的,这很显然

fins.close();
printf("%s\n",read_buf);

system("pause");
return 0 ;
}

运行结果:Hello world


程序2:

#include <stdio.h>
#include <fstream>

using namespace std;
int main()
{
char *read_buf = "Hello world!<!----//----->Hello china!";
char *end = strstr(read_buf, "<!");
*(end - 1) = '\0';
//*(end + 1)= '\0';//这样做,也是错误的,显然此处不是因为越界

printf("%s\n",read_buf);

system("pause");
return 0 ;
}

通过编译,但运行失败,中止在“*(end - 1) = '\0';”
昨天也发帖问大家“*(end - 1) = '\0';”这样使用是否有错,有人说越界了,那么“程序1”为何运行成功?
程序1和程序2中,read_buf所指向的内存有何不同吗?所以才导致这种问题?
...全文
193 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
karl_max 2009-12-03
  • 打赏
  • 举报
回复
正常情况下:
char *read_buf = "Hello world!<!----//----->Hello china!";
应该声明为:
const char *read_buf = "Hello world!<!----//----->Hello china!";
sduxiaoxiang 2009-12-03
  • 打赏
  • 举报
回复
指向的是常量区的数据
mstlq 2009-12-03
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 beyond0824 的回复:]
引用 2 楼 mstlq 的回复:
请勿试图修改字符常量区里面的数据
C/C++ code#include <stdio.h>
#include <fstream>usingnamespace std;int main()
{char  read_buf[]="Hello world! <!----//----->Hello china!";//这样应该就没问题了char*end= strstr(read_buf," <!");*(end-1)='\0';//*(end + 1)= '\0';//这样做,也是错误的,显然此处不是因为越界    printf("%s\n",read_buf);

    system("pause");return0 ;
}

那第一个程序中的read_buf指向的内容属于什么?
[/Quote]

read_buf = new char[length + 1]; //从堆(heap)上申请的内存空间
江南烟雨梦 2009-12-03
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 mstlq 的回复:]
请勿试图修改字符常量区里面的数据
C/C++ code#include<stdio.h>
#include<fstream>usingnamespace std;int main()
{char read_buf[]="Hello world!<!----//----->Hello china!";//这样应该就没问题了char*end= strstr(read_buf,"<!");*(end-1)='\0';//*(end + 1)= '\0';//这样做,也是错误的,显然此处不是因为越界 printf("%s\n",read_buf);

system("pause");return0 ;
}
[/Quote]
那第一个程序中的read_buf指向的内容属于什么?
mstlq 2009-12-03
  • 打赏
  • 举报
回复
请勿试图修改字符常量区里面的数据
#include <stdio.h>
#include <fstream>

using namespace std;
int main()
{
char read_buf[] = "Hello world!<!----//----->Hello china!";//这样应该就没问题了
char *end = strstr(read_buf, "<!");
*(end - 1) = '\0';
//*(end + 1)= '\0';//这样做,也是错误的,显然此处不是因为越界
printf("%s\n",read_buf);

system("pause");
return 0 ;
}
灌水九段 2009-12-03
  • 打赏
  • 举报
回复
因为第二种情况下 char *read_buf 指向的是一个字符串常量 是不能修改的!

65,183

社区成员

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

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