【问题标题】:Why is the param of strlen a "const"?为什么 strlen 的参数是“const”?
【发布时间】:2012-01-05 18:42:08
【问题描述】:

我正在学习 C 语言。

我的问题是: 为什么 strlen 的参数是“const”?

size_t strlen(const char * string);

我想这是因为字符串是一个地址,所以初始化后它不会改变。如果这是正确的,这是否意味着每次使用指针作为参数构建函数时,都应该将其设置为常量?

如果我决定构建一个将 int 变量设置为 double 的函数,是否应该将其定义为:

void timesTwo(const int *num)
{
    *num *= 2;
}

void timesTwo(int *num)
{
    *num *= 2;
}

或者根本没有区别?

【问题讨论】:

  • 您的一个timesTwo 示例编译;另一个没有。

标签: c function pointers prototype strlen


【解决方案1】:

C 字符串是指向以零结尾的字符序列的指针。在char * 前面的const 向编译器和调用函数的程序员表明strlen 不会修改string 指针指向的数据。

这点看strcpy比较容易理解:

char * strcpy ( char * destination, const char * source );

它的第二个参数是const,但它的第一个参数不是。这告诉程序员第一个指针指向的数据可能会被函数修改,而第二个指针指向的数据在从strcpy返回时将保持不变。

【讨论】:

    【解决方案2】:

    strlen 函数的参数是一个指向 const 的指针,因为函数不应该改变指针指向的东西——它只应该对字符串做一些事情而不改变它。

    在你的函数'timesTwo'中,如果你打算改变'num'指向的值,你不应该把它作为一个指向常量的指针传入。所以,使用第二个例子。

    【讨论】:

      【解决方案3】:

      基本上,该函数承诺它不会通过该指针修改输入字符串的内容;它说表达式*string 可能不会被写入。

      以下是const 限定符的各种排列:

      const char *s;            // s may be modified, *s may not be modified
      char const *s;            // same as above
      char * const s;           // s may not be modified, *s may be modified
      const char * const s;     // neither s nor *s may be modified
      char const * const s;     // same as above
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        • 2017-01-11
        相关资源
        最近更新 更多