代码之家  ›  专栏  ›  技术社区  ›  Tim unnamed eng

字符数组的字符串初始值设定项

  •  33
  • Tim unnamed eng  · 技术社区  · 15 年前

    对于数组衰减到指针的情况,请遵循以下规则:

    出现在表达式中的类型array-of-t的左值[参见问题2.5]将衰减(有三个例外)为指向其第一个元素的指针;结果指针的类型为pointer-to-t。

    (例外情况是,当数组是sizeof或&运算符的操作数,或是字符数组的字符串初始值设定项时。)

    当数组是“字符数组的字符串初始值设定项”时,如何理解这种情况?请举个例子。

    谢谢!

    4 回复  |  直到 10 年前
        1
  •  44
  •   Géry Ogam    10 年前

    数组不衰减为指针的三个例外是:

    例外1。 _ sizeof .

    int main()
    {
       int a[10];
       printf("%zu", sizeof(a)); /* prints 10 * sizeof(int) */
    
       int* p = a;
       printf("%zu", sizeof(p)); /* prints sizeof(int*) */
    }
    

    例外2。 _ & 操作员。

    int main()
    {
        int a[10];
        printf("%p", (void*)(&a)); /* prints the array's address */
    
        int* p = a;
        printf("%p", (void*)(&p)); /*prints the pointer's address */
    }
    

    例外情况3. _“,当数组用文字字符串初始化时。

    int main()
    {
        char a[] = "Hello world"; /* the literal string is copied into a local array which is destroyed after that array goes out of scope */
    
        char* p = "Hello world"; /* the literal string is copied in the read-only section of memory (any attempt to modify it is an undefined behavior) */
    }
    
        2
  •  8
  •   John Bode    15 年前

    假设声明

    char foo[] = "This is a test";
    char *bar  = "This is a test";
    

    在这两种情况下,字符串文本的类型“ This is a test 是“15个字符数组”。在大多数情况下,数组表达式都是从类型“n-element array of t”隐式转换为“pointer to t”,表达式的计算结果是数组第一个元素的地址。在声明中 bar 就这样。

    在声明中 foo 但是,表达式正用于初始化另一个数组中的内容,因此 转换为指针类型;相反, 内容 将字符串文本复制到 .

        3
  •  5
  •   Eli Bendersky    15 年前

    这是字符数组的文本字符串初始值设定项:

    char arr[] = "literal string initializer";
    

    也可能是:

    char* str = "literal string initializer";
    

    K&R2的定义:

    字符串文字,也称为字符串 常量,是字符序列 用双引号括起来,如中所示 “……”字符串的类型``数组为 字符“”和存储类静态 (见下文第A.3段)并初始化 使用给定的字符。是否 相同的字符串文本是不同的 是否定义了实现,以及 程序试图 更改字符串文本未定义。

        4
  •  2
  •   jamesdlin    15 年前

    似乎您从comp.lang.c常见问题解答中引用了这句话(可能是旧版本,也可能是打印版本;它与在线版本的当前状态不太匹配):

    http://c-faq.com/aryptr/aryptrequiv.html

    相应的部分链接到FAQ的其他部分,以详细说明这些异常。在您的案例中,您应该看到:

    http://c-faq.com/decl/strlitinit.html