【问题标题】:How come this const char* can't be modified after actually modifying it?为什么这个 const char* 实际修改后不能修改?
【发布时间】:2019-07-26 05:15:41
【问题描述】:

举个例子:

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*,然后我能够重新为其分配另一个值(内存中的实际数据 - 而不是内存地址本身)。

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

这是为什么呢?

【问题讨论】:

  • 在您的示例中,what 是可修改的。它指向的内容是不可修改的。
  • 查看这个问题了解如何阅读指针声明:stackoverflow.com/questions/1143262/…
  • 如果你想要一个指向你正在寻找的 const 事物的 const 指针 const char* const what

标签: c++ arrays pointers constants


【解决方案1】:

const 适用于指向的字符而不是指针本身!因此,您可以指向任何您想要的 C 字符串,但不能更改这些字符串的字符。

为了例子的简单起见,我将使用另一种类型来说明这一点(C-strings literals不能修改):

其实你有这样的东西

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指向的指针:

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

然后您可以将两者混合使用,永远不要更改指针或指向的 int:

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

【讨论】:

  • @TedLyngmo 是的,我正在考虑对此说些什么,但您可能会有所帮助,因为它会使示例过于复杂...任何想法?使用其他类型可能吗?
  • 现在好多了!
【解决方案2】:

在这段代码中,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 char 的 const 指针,把它写在不同的地方:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2016-01-20
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多