How to print a char array in C through printf? [closed]

The code posted is incorrect: a_static and b_static should be defined as arrays.

There are two ways to correct the code:

  • you can add null terminators to make these arrays proper C strings:

    #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;
    }
    
  • Alternately, printf can print the contents of an array that is not null terminated using the precision field:

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

    The precision given after the . specifies the maximum number of characters to output from the string. It can be given as a decimal number or as * and provided as an int argument before the char pointer.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)