为什么这个常量字符*在实际修改后无法修改?

How come this const char* can't be modified after actually modifying it?

本文关键字:修改 常量 字符 为什么      更新时间:2023-10-16

以此示例:

int main()
{
   const char* what = "Is This";
   what = "Interesting";
   cout << *what;
   what[3] = 'a'; // Sytax Error: expression must be a modifiable lvalue
   cout << *what;
   return 0;
}

所以我将what声明为const char*,并且我能够将其重新分配另一个值(内存中的实际数据 - 不是内存地址本身)。

但是,它告诉我我无法更改第四位置的角色!

为什么?

在此代码中, what是const char。

您可以更改what,但是您不能更改*what

如果要声明指向const char的const指针,则需要两次编写const

const char *const what = "Is This";
// what is const
what = "Interesting"; // Error
// *what is also const
what[4] = 'x';        // Error

如果您想要const指针指向非const char,请在另一个地方写下:

char isthis[] = "Is This";
char interesting[] = "Interesting";
char *const what = isthis;
// what is const
what = interesting; // Error
// *what is not const
what[4] = 'x';      // Ok

const适用于指向指针本身的字符!因此,您可以指出所需的任何C弦,但不能更改这些字符串的性格。

为示例的简单起见,我将使用另一种类型来说明该点(C-strings文字无法修改):

您实际上有类似的东西

const int i = 666;
const int j = 999;
const int *pi = &i;
pi = &j;
// *pi=444; is invalid, can't change the int pointed by pi

您可以构建一个无法更改的指针,但插入了:

int i = 666;
int j = 999;
int *const pi = &i;
*pi = 999;
// pi = &j; is invalid, pi will always point to i

然后您可以混合两者,切勿更改指针或插入率:

const int i = 666;
const int j = 999;
const int *const pi = &i;
// pi = &j; is invalid
// *pi = 444; is invalid