数组的字符串文字

问题描述

#include <stdio.h>

int main(void) {
    char a[] = "125"; // (int)1,(int)2,(int)5. But array 'a' has a type char. So int is in char. ???
    printf("%s",a);
}

在该代码中,字符串文字的每个元素都具有int类型。但是数组a的类型为char。

在C99 6.4.5中$ 2片段
相同的注意事项适用于字符串中序列的每个元素 文字或宽字符串文字,就好像它是整数字符常量还是宽 字符常数

在C99 6.4.5中$ 5片段
对于字符串文字,数组元素具有 类型为char,并使用多字节字符的各个字节进行初始化 顺序

我认为它们不兼容,这对我来说是一个矛盾。我的想法怎么了?

解决方法

不,这是字符串文字。

引用C11,第6.4.5章,字符串文字:

字符串文字是由双引号引起的零个或多个多字节字符的序列,例如“ xyz”。[...]

详细地说,字符串liteal的可接受语法为:

string-literal:
                 encoding-prefixopt " s-char-sequenceopt "
          encoding-prefix:
                 u8
                 u
                 U
                 L
          s-char-sequence:
                 s-char
                 s-char-sequence s-char
          s-char:
                 any member of the source character set except
                              the double-quote ",backslash \,or new-line character
                 escape-sequence

然后是“源字符集”,指的是(第5.2.1 / P3章)

Both the basic source and basic execution character sets shall have the following members: the 26 uppercase letters of the Latin alphabet

         A   B   C   D   E   F   G   H   I   J   K   L   M
         N   O   P   Q   R   S   T   U   V   W   X   Y   Z
the 26 lowercase letters of the Latin alphabet
         a   b   c   d   e   f   g   h   i   j   k   l   m
         n   o   p   q   r   s   t   u   v   w   x   y   z
the 10 decimal digits
         0   1   2   3   4   5   6   7   8   9
the following 29 graphic characters
         !   "   #   %   &   '   (   )   *   +,-   .   /   :
         ;   <   =   >   ?   [   \   ]   ^   _   {   |   }   ~

因此,类似"123"的构造是字符串文字,而不是char中/中持有的单个整数。

,

实际上,它们只是三个字符,而不是三个整数。就像写char a [] =“ abc”; 不要被1 2 3是数字符号这一事实所迷惑。

,
char a[] = "125"; 

在该代码中,字符串文字的每个元素都具有int类型。但是数组a的类型为char。

否,它是5的事实并不意味着它必须是int。必须根据其声明位置/方式的上下文来确定其类型。

在您的情况下,5的类型为char,因为它是字符串文字的一部分。

还请注意,5可以是任何其他类型之一,例如unsigned intunsigned shortdouble等。因此,您必须再次查看它在声明中的方式第一名。