指向 char 数组的指针的运行时中断错误
C++ - 该程序在第 2 行给出运行时中断错误。
char * ptr = "hello";
(*ptr)++; // should increment 'h' to 'i'
cout<<ptr<<endl; // should display 'iello'
test.exe 中 0x004114b0 处出现未处理的异常:0xC0000005:访问冲突写入位置 0x00417830。
知道为什么会出现此错误吗?而如果我运行以下代码,它工作得绝对正常。
char arr[] = "hello";
char * ptr = arr;
(*ptr)++; // increments 'h' to 'i'
cout<<ptr<<endl; // displays 'iello'
C++ - This program gives a run-time break error at line 2.
char * ptr = "hello";
(*ptr)++; // should increment 'h' to 'i'
cout<<ptr<<endl; // should display 'iello'
Unhandled exception at 0x004114b0 in test.exe: 0xC0000005: Access violation writing location 0x00417830.
Any idea why it is giving this error? Whereas if I run the following code, it works absolutely fine.
char arr[] = "hello";
char * ptr = arr;
(*ptr)++; // increments 'h' to 'i'
cout<<ptr<<endl; // displays 'iello'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为您正在尝试更改只读内存。有一个 C FAQ 就足够了,即使这是一个 C++ 问题。
基本上,当说
char *ptr = "hello"
时,编译器可以自由地将“hello”置于只读状态内存,因此尝试写入它是不安全的。
另一个 C FAQ 可能有用:
Because you are trying to change read-only memory. There is a C FAQ which is adequate, even if this is a C++ question.
Basically when saying
char *ptr = "hello"
the compiler is free to place "hello" in read-onlymemory so it's not safe to try to write to it.
Another C FAQ might be useful:
当你声明 char * ptr = "hello";
ptr 指向一个常量字符串
这意味着当你说 ptr++ 时 ,
您正在尝试更改不正确的基地址
When you declare char * ptr = "hello";
it means ptr is pointing to a constant string
when you say ptr++ ,
You are trying to change the base address which is not correct