Having difficulty printing strings

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

    Expanding on the previous answers, the strings appear to be joined due to the order the variables are stored in the stack memory. This won't always work the same on every processor architecture or compiler (optimiser settings can change this behaviour too).

    0 讨论(0)
  • 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";
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-22 07:18

    A string is a null terminated char array in C.

    Change

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

    to

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

    (which is the same as char string2[] = "12ab";)

    0 讨论(0)
  • 2021-01-22 07:20

    You need to terminate your array with NULL character as

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

    When you are doing the scanf(), string1 is stored in next memory so it is printing string2 with string1. It will print upto it gets \0 so its Undefined Behavior

    0 讨论(0)
提交回复
热议问题