改变c++中char *const所指向的数据时的访问冲突

Access violation in changing data pointed to by char *const in C++

本文关键字:数据 访问冲突 c++ char const 改变      更新时间:2023-10-16

我读了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".