【问题标题】:C - Difference between quotation and apostrophe ( " vs ' ) [duplicate]C - 引号和撇号之间的区别(“ vs ')[重复]
【发布时间】:2015-12-20 06:42:12
【问题描述】:

在 C 中,人们注意到这两种指定的语法之间存在差异。观察

 char test[5] = {"c", "o", "o", "l", "\0"}; // with quotation

带来错误:

error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')
error: excess elements in char array initializer
error: (near initialization for 'test')

在哪里

char test[5] = {'c', 'o', 'o', 'l', '\0'}; // with apostrophe

编译良好。这是什么原因?

【问题讨论】:

  • 'x' 是一个字符文字。 "x" 是一个包含一个字符的字符串字面量。
  • 单个字符与字符串(字符序列)。

标签: c syntax


【解决方案1】:

这个数组中的元素是字符(每个1字节):

char test[5] = {'c', 'o', 'o', 'l', '\0'};

这是一个以 null 结尾的 C 字符串。它在内存中的表示方式完全相同。它正好由 5 个字节组成:字母“cool”和终止空字符:

char test2[5] = {"cool"};

这由两个字节组成:

char test3[] = "c";

您的原始示例是一个 2 字节字符串数组。与前面的示例不同,它实际上是一个 2 级数组。您必须这样声明:

char *test[] = {"c", "o", "o", "l", "\0"};

【讨论】:

  • @Blastfurnace - 这是一个错字,感谢您指出:)
【解决方案2】:

在 C 中,

两个单引号'用于表示一个字符常量。
两个双引号" 用于表示字符串文字。

一个字符常量只能表示一个字符。 'ab' 不是有效的字符常量。

一个字符串可以包含多个字符。

【讨论】:

    【解决方案3】:

    "x" 不是字符,它是字符串文字。它与'x''\0' 两个字符的数组相同。

    我是这样想的:

           _ _ _ _ _
    "x" => |'x'|'\0'| 
           - - - - -  
    

    【讨论】:

      【解决方案4】:
      char test[5] = {'c', 'o', 'o', 'l', '\0'}; // with apostrophe
      

      是正确的语法,因为正如您所声明的,test 是一个可以存储 5 个字符的字符数组。

      char* test[5] = {"c", "o", "o", "l", "\0"}; // 带引号

      这是可以接受的,因为您声明 test 是一个指向字符串的指针数组。

      在ideone.com中运行下面的代码看看。

      #include <stdio.h>
      
      int main(void) {
      // your code goes here
      
      char* teststring[5] = {"c", "o", "o", "l", "\0"}; // with quotation
      
      char testchar[5] = {'c', 'o', 'o', 'l', '\0'};
      printf("%s\n", teststring[2]);
      
      printf("%c\n", testchar[2]);
      
      return 0;
      }
      

      【讨论】:

        【解决方案5】:

        在 C 中,当您使用单引号时,它表示一个字符,双引号表示字符串文字。而且由于您将数组声明为 char 因此它不能在其中存储字符串。

        【讨论】:

          猜你喜欢
          • 2013-07-21
          • 1970-01-01
          • 1970-01-01
          • 2020-07-31
          • 2021-10-26
          • 1970-01-01
          • 2018-08-29
          • 1970-01-01
          • 2012-05-05
          相关资源
          最近更新 更多