【问题标题】:c++ i cant understand the difference between const char* and char* [duplicate]c++ 我无法理解 const char* 和 char* 之间的区别 [重复]
【发布时间】:2016-11-17 18:06:03
【问题描述】:

我知道你会说它是重复的,但相信我,我读了很多关于这个的文章,但我仍然无法理解差异是什么,所以我举了两个例子。
1.

int strlen(const char* string)
{
   int i = 0;
   while (string[i] != '\0')
   {
       ++i;
   }
   return i;
}

2.

int strlen(char* string)
{
   int i = 0;
   while (string[i] != '\0')
   {
       ++i;
   }
   return i;
}

主要:

int main() 
{
    char str[] = "Hello";
    cout << strlen(str) << endl;
}

第二个可以工作并且不会出错,而第一个不会。

【问题讨论】:

  • 第一个错误是什么?
  • 也可以考虑char *const,这与其他的不同。
  • 第一个应该可以正常工作。
  • 除非他包含&lt;string.h&gt;,在这种情况下,它与标准库函数有歧义。
  • 第一个works just fine.

标签: c++ char constants


【解决方案1】:

案例 1:您可以不更改 string 的值,它是只读的。用于防止函数改变参数值(最小权限原则)

案例2:您可以更改string的值。

另外,检查来自 cmets 的链接。

【讨论】:

  • 不,不正确。您可以在任一函数中更改string 的值。首先,您不能更改任何给定N 的string[N] 的值。
  • 没错,你可以改变指针的值。我说的是const char * const
猜你喜欢
  • 2011-03-07
  • 2018-11-05
  • 2013-04-23
  • 2011-02-25
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
相关资源
最近更新 更多