如何通过printf在C中打印字符数组?

31

这导致分段错误。需要进行什么更正?

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);
}

char *a_static 使用一个指针。 - user5063151
请查看 https://dev59.com/F1wY5IYBdhLWcg3wEEV2。 - Martin James
可能是分段错误常见原因列表的重复。 - Cœur
4个回答

56

所发布的代码有误:a_staticb_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可以使用精度字段打印未以空字符结尾的数组的内容:

    #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;
    }
    

    .后面给出的精度指定了从字符串中输出的最大字符数。它可以作为十进制数给出,也可以作为*给出,并在char指针之前作为int参数提供。


1
由于以下语句,导致出现分段错误。
char a_static = {'q', 'w', 'e', 'r'};

a_static 应该是 字符数组,用于存储多个字符。像这样制作它

 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'};

啊!感谢这个错误。 - Aquarius_Girl
1
你还应该在char数组中添加'\0'字符以防止溢出。 - Anirudh

1
你需要使用数组而不是声明。
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;
}

0
问题在于您正在使用C风格字符串,而C风格字符串以零终止。 例如,如果您想通过使用char数组打印“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 是 "alien"

回到你的代码,它应该长这样:

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等)需要零知道字符串何时结束

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


这在各个方面都有问题,部分也是错误的。首先:指针永远不能代替数组。如果有人想回答带有错误代码和基础不足的问题,他们至少应该非常正确地理解它,这样 OP 就不需要购买教材来正确学习语言,这才是正确的方式。 - too honest for this site

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接