如何通过printf在C中打印一个char数组?

Aqu*_*irl 4 c arrays printf char

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

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);
}
Run Code Online (Sandbox Code Playgroud)

chq*_*lie 9

发布的代码是不正确: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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者,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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    后面给出的精度.指定要从字符串输出的最大字符数。它可以以十进制数形式给出,也可以以as形式给出,并可以作为指针之前的参数*提供。intchar