【问题标题】:C: declare a constant pointer to an array of constant charactersC:声明一个指向常量字符数组的常量指针
【发布时间】:2011-04-01 01:51:00
【问题描述】:

我正在尝试理解数组声明、常量以及它们产生的变量类型。

以下是允许的(由我的编译器):

      char s01[] = "abc" ;  // typeof(s01) = char*
const char s02[] = "abc" ;  // typeof(s02) = const char* (== char const*)
char const s03[] = "abc" ;  // typeof(s03) = char const* (== const char*)

或者,我们可以手动声明数组大小:

      char s04[4] = "abc" ;  // typeof(s04) = char*
const char s05[4] = "abc" ;  // typeof(s05) = const char* (== char const*)
char const s06[4] = "abc" ;  // typeof(s06) = char const* (== const char*)

如何获得const char* const 类型的结果变量?以下是不允许的(我的编译器):

const char s07 const[] = "abc" ;
char const s08 const[] = "abc" ;
const char s09[] const = "abc" ;
char const s10[] const = "abc" ;
const char s11 const[4] = "abc" ;
char const s12 const[4] = "abc" ;
const char s13[4] const = "abc" ;
char const s14[4] const = "abc" ;

谢谢

【问题讨论】:

标签: c arrays pointers char constants


【解决方案1】:

您的第一个 typeof cmets 并不正确。 s01的类型是char [4]s02s03的类型是const char [4]。当在表达式中使用而不是 &sizeof 运算符的主题时,它们将分别计算为 char *const char * 类型的右值,指向数组的第一个元素。

您不能以这样一种方式声明它们,即它们会衰减为本身是 const 限定的右值;拥有一个 const 限定的右值实际上没有任何意义,因为不能分配右值。这就像说你想要一个5 类型的常量const int 而不是int

【讨论】:

    【解决方案2】:

    使用cdecl:

    cdecl> declare foo as constant pointer to array of constant char
    Warning: Unsupported in C -- 'Pointer to array of unspecified dimension'
            (maybe you mean "pointer to object")
    const char (* const foo)[]
    cdecl> declare foo as constant pointer to array 4 of constant char
    const char (* const foo)[3]
    cdecl> declare foo as constant pointer to constant char
    const char * const foo
    

    C 中很少使用指向数组的指针;通常 API 函数需要一个指向第一个元素的指针。

    【讨论】:

      【解决方案3】:

      s01 等并不是真正的指针类型,它们是数组类型。从这个意义上说,它们的行为已经有点像const 指针(例如,您不能重新分配s01 以指向其他地方)。

      【讨论】:

        【解决方案4】:
        const char *const s15 = "abc";
        

        【讨论】:

        • 从右到左阅读有助于理解什么是不变的。例如。 char *const s15 表示指向字符的常量指针。 char const *s15 表示指向常量字符的指针。 char const *const s15 表示常量指针到常量字符。试试吧!从右到左!
        • @PP:不过,从右到左的规则并不适用于所有情况。例如int blah[5][2]。我发现的关于如何阅读声明符的最佳总结在这里:msdn.microsoft.com/en-us/library/1x82y1z4.aspx
        • @PP:它不是从右到左,而是从左到右,它是由内向外
        • 这是我正在寻找的答案。我坚持 [] 在堆栈上分配的想法(在函数中声明时)。如果它是指向常量字符数组的常量指针,我不需要在堆栈上分配。在程序数据空间中一次就可以了。谁知道“abc”在这里分配的位置,谁在乎。我们使用s15 作为绝对常数。我们不能重新分配指针s15,也不能更改它指向的值("abc")。谢谢!
        • C 声明应按顺时针方向阅读:c-faq.com/decl/spiral.anderson.html
        猜你喜欢
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 2013-08-02
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 2020-10-23
        相关资源
        最近更新 更多