改变c++中char *const所指向的数据时的访问冲突
Access violation in changing data pointed to by char *const in C++
我读了Steve Qualine写的c++ hacks,上面写着:
char *const ptr;//statement 1
指针不受const关键字的影响,下面的操作是合法的。
*ptr = 'S';//statement 2
但是当我写上面的代码时,statement 1
本身给了我错误,说指针必须初始化,当我初始化它时,statement 2
给了我访问冲突。
我错过了什么?
如果你想创建一个变量char *const ptr
,你需要在声明时准备好内存供它指向。这是因为指针(与它指向的内存相反)是const,必须在声明时设置。
这与const char *
相反,其中指向的内存是const,但指针不是,因此您可以将其更改为指向内存中const char
的不同区域,但您不能更改它指向的内存。
char buf[16] = "Hello World";
char *const ptr = buf; // ptr and buf both point to "Hello World".
*ptr = 'J'; // ptr and buf now point to "Jello World"
ptr = "Another string"; // Error, cannot assign to a variable that is const
const char *cptr = buf; // cptr points to "Jello World".
*cptr = 'H'; // Error, cannot assign to a variable that is const
cptr = "Another string"; // cptr now points to "Another string".
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 读取访问冲突. _Mycont 在 C++ 中将 udp 数据放入向量时出现 nullptr 错误
- 从网络数据包复制一串 wchar 时访问冲突
- 字符串数据成员的指针错误 - 获取访问冲突
- C++-构造ICMP数据包时发生访问冲突
- 改变c++中char *const所指向的数据时的访问冲突
- C++OpenCV mat.at在使用数据时产生访问冲突
- 在向数组写入数据时发生写访问冲突