代码之家  ›  专栏  ›  技术社区  ›  Aquarius_Girl

如何通过printf在C中打印字符数组?[已关闭]

  •  27
  • Aquarius_Girl  · 技术社区  · 6 年前

    这会导致分段错误。 需要纠正什么?

    int main(void)
    {
        char a_static = {'q', 'w', 'e', 'r'};
        char b_static = {'a', 's', 'd', 'f'};
    
        printf("\n value of a_static: %s", a_static);
        printf("\n value of b_static: %s\n", b_static);
    }
    
    4 回复  |  直到 6 年前
        1
  •  46
  •   chqrlie    6 年前

    发布的代码不正确: a_static b_static 应定义为数组。

    有两种方法可以更正代码:

    • 您可以添加空终止符以使这些数组适合C字符串:

      #include <stdio.h>
      
      int main(void) {
          char a_static[] = { 'q', 'w', 'e', 'r', '\0' };
          char b_static[] = { 'a', 's', 'd', 'f', '\0' };
      
          printf("value of a_static: %s\n", a_static);
          printf("value of b_static: %s\n", b_static);
          return 0;
      }
      
    • 或者, printf 可以使用精度字段打印以非null结尾的数组的内容:

      #include <stdio.h>
      
      int main(void) {
          char a_static[] = { 'q', 'w', 'e', 'r' };
          char b_static[] = { 'a', 's', 'd', 'f' };
      
          printf("value of a_static: %.4s\n", a_static);
          printf("value of b_static: %.*s\n", (int)sizeof(b_static), b_static);
          return 0;
      }
      

      . 指定要从字符串输出的最大字符数。它可以作为十进制数或 * 并作为 int 前的参数 char 指针。

        2
  •  1
  •   Achal    6 年前

    这会导致分段错误? 因为下面的陈述

    char a_static = {'q', 'w', 'e', 'r'};
    

    a_static 应该是 char array 保存多个字符。让它像

     char a_static[] = {'q', 'w', 'e', 'r','\0'}; /* add null terminator at end of array */
    

    类似于 b_static

    char b_static[] = {'a', 's', 'd', 'f','\0'};
    
        3
  •  1
  •   Karthik Vg    6 年前

    您需要使用数组而不是声明

    a_static
    b_static
    

    作为变量

    看起来是这样的:

    int main()
    {
      char a_static[] = {'q', 'w', 'e', 'r','\0'};
      char b_static[] = {'a', 's', 'd', 'f','\0'};
      printf("a_static=%s,b_static=%s",a_static,b_static);
      return 0;
    }
    
        4
  •  0
  •   NotMe    6 年前

    例如,如果要使用字符数组打印“alien”:

    char mystring[6] = { 'a' , 'l', 'i', 'e' , 'n', 0}; //see the last zero? That is what you are missing (that's why C Style String are also named null terminated strings, because they need that zero)
    printf("mystring is \"%s\"",mystring);
    

    输出应为:

    mystring是“外星人”

    回到您的代码,它应该如下所示:

    int main(void) 
    {
      char a_static[5] = {'q', 'w', 'e', 'r', 0};
      char b_static[5] = {'a', 's', 'd', 'f', 0}; 
      printf("\n value of a_static: %s", a_static); 
      printf("\n value of b_static: %s\n", b_static); 
      return 0;//return 0 means the program executed correctly
    }
    

    顺便说一下,您可以使用指针代替数组(如果不需要修改字符串):

    char *string = "my string"; //note: "my string" is a string literal
    

    此外,还可以使用字符串文字初始化字符数组:

    char mystring[6] = "alien"; //the zero is put by the compiler at the end 
    

    另外:在C样式字符串上操作的函数(例如printf、sscanf、strcmp、strcpy等)需要零才能知道字符串的结束位置

    希望你从这个答案中学到一些东西。