【问题标题】:How to declare a constant "mutable pointer" to an immutable block of memory如何声明一个指向不可变内存块的常量“可变指针”
【发布时间】:2014-09-29 21:49:08
【问题描述】:

我想知道如何在 C99 中声明 (a const pointer to (a mutable pointer to (a const type)))

假设我有这个呼叫站点:

const uint8_t* result;
create(&result);

在这种情况下,void create(const uint8_t * const * resultPtr) 是声明被调用者的正确方法还是意味着意外?我不需要重新分配resultPtr,调用者不应该[从这个角度]*resultPtr[0],但我的函数需要分配*resultPtr = …

【问题讨论】:

    标签: c c99 const-correctness


    【解决方案1】:

    我们问cdecl

    $ cdecl declare p as const pointer to pointer to const char
    const char ** const p
    

    这个声明可以从右到左完整阅读得到英文版(记住const charchar const是一样的)。

    【讨论】:

    • 哦,我忘记了所有关于 cdecl 的事情。非常感谢!
    • 可悲的是,cdecl 网站似乎已成为万事大吉。 :-(
    【解决方案2】:

    一些经验法则:

    • <type> * const <varName> = <value> 始终创建指向 <type> 内容的不可变指针 <varName>。请考虑星号右侧的const * const
    • 所有这些选项都会创建不可变的内容:
      • const <type> <pointers> <varName> = <value>
      • <type> const <pointers> <varName> = <value>
      • const <type> const <pointers> <varName> = <value>
      • <type> const const <pointers> <varName> = <value>

    警告:最后两个选项返回一个

    警告:重复的 'const' 声明说明符 [-Wduplicate-decl-specifier]

    在 Clang 编译器上,应该被视为不好的做法。

    所以要有一个不可变的指针指向一个不可变的uint8_t的可变指针,所有这些选项都有效:

    • const uint8_t * * const result = NULL
    • uint8_t const * * const result = NULL
    • const uint8_t const * * const result = NULL
    • uint8_t const const * * const result = NULL

    但是,第二个选项

    uint8_t const * * const result = NULL;
    

    恕我直言,这似乎是最易读和最规范的编写方式。您可能会发现this post 在这方面也提供了丰富的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2011-04-01
      • 2019-10-06
      • 1970-01-01
      相关资源
      最近更新 更多