Having difficulty printing strings

后端 未结 5 517
走了就别回头了
走了就别回头了 2021-01-22 06:35

When I run the program, the second printf() prints string2 with whatever was scanned into string1 attached to the end.

e.g.

5条回答
  •  深忆病人
    2021-01-22 07:14

    If the format specifier %s does not have the precision flag then the function outputs characters until it encounteres zero character '\0'

    Character array string2 is defined such a way that it does not have the terminating zero

    char string2[4]={'1','2','a','b'};
    

    So the function outputs characters beyond the array until it meets zero character.

    You could use the precision flag that to specify explicitly how many characters you are going to output. For example

    printf("Is before \"%4.4s\":",string2);    
    

    Or you could define the array that includes the terminating zero. For example

    char string2[5] = { '1', '2', 'a', 'b', '\0' };
    

    Take into account that in this case the size of the array if it is specified shall be equal at least to 5 ( though the size can be greater than 5; in this case other characters that do not have initializers will be zero-initialized)

    or simply

    char string2[] = { "12ab" };
    

    or without braces

    char string2[] = "12ab";
    

提交回复
热议问题