无法取消引用
Unable to dereference
在下面的代码中,为什么无法进行这种取消引用:*arr = 'e'
.输出不应该是字符'e'
吗?
int main ()
{
char *arr = "abt";
arr++;
* arr='e'; // This is where I guess the problem is occurring.
cout << arr[0];
system("pause");
}
我收到以下错误:
数组.exe中0x00a91da1时未处理的异常: 0xC0000005:访问冲突写入位置0x00a97839。
"abt"
是所谓的字符串文字常量,任何修改它的尝试都会导致未定义的行为*arr='e';
。
int main ()
{
char *arr= "abt"; // This could be OK on some compilers ... and give an access violation on others
arr++;
*arr='e'; // This is where I guess the problem is occurring.
cout<<arr[0];
system("pause");
}
相比之下:
int main ()
{
char arr[80]= "abt"; // This will work
char *p = arr;
p++; // Increments to 2nd element of "arr"
*(++p)='c'; // now spells "abc"
cout << "arr=" << arr << ",p=" << p << "n"; // OUTPUT: arr=abc,p=c
return 0;
}
此链接和图表解释了"为什么":
http://www.geeksforgeeks.org/archives/14268
C 程序的内存布局
C 程序的典型内存表示包括以下内容 部分。
- 文本段
- 初始化的数据段
- 未初始化的数据段
- 叠
- 堆
像 const char* 字符串 = "hello world" 这样的 C 语句使 字符串文字"hello world"存储在初始化的只读中 区域中和字符指针变量字符串初始化 读写区域。
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++ 关于指针取消引用的技术问题
- 没有取消引用/解包对象的标准方法?
- 列表 iter 不取消引用 使用列表进行插入排序
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 取消引用结束指针到数组类型的一个
- 取消引用向量时出现问题
- 取消引用指向整数的指针时获得不同的结果
- C++:取消引用十六进制值,有点语法问题
- C/C++ 取消引用错误:在空检查之前取消引用
- 取消引用后C++空测试
- 立即取消引用unique_ptr
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 取消引用 void 指针以将值分配给结构
- boost_multi_index迭代器取消引用给出常量
- 为什么"std::uninitialized_copy"通常取消对未初始化内存的迭代器的引用不是未定
- 矢量迭代器不能与 std::shared_ptr<> 取消引用