Having difficulty printing strings

后端 未结 5 514
走了就别回头了
走了就别回头了 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:16

    In your code

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

    string2 is not null-terminated. Using that array as an argument to %s format specifier invokes undefined behavior, as it runs past the allocated memory in search of the null-terminator.

    You need to add the null-terminator yourself like

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

    to use string2 as a string.

    Also, alternatively, you can write

    char string2[ ]= "12ab";
    

    to allow the compiler to decide the size, which considers the space for (and adds) the null-terminator.

    Same goes for abc also.

    That said, you're scanning into string1 and printing string2, which is certainly not wrong, but does not make much sense, either.

提交回复
热议问题