Strings without a '\0' char?

后端 未结 6 542
醉梦人生
醉梦人生 2020-12-10 18:58

If by mistake,I define a char array with no \\0 as its last character, what happens then?

I\'m asking this because I noticed that if I try to iterate th

6条回答
  •  孤城傲影
    2020-12-10 19:21

    If you define a char array without the terminating \0 (called a "null terminator"), then your string, well, won't have that terminator. You would do that like so:

    char strings[] = {'h', 'e', 'l', 'l', 'o'};
    

    The compiler never automatically inserts a null terminator in this case. The fact that your code stops after "+2" is a coincidence; it could just as easily stopped at +50 or anywhere else, depending on whether there happened to be \0 character in the memory following your string.

    If you define a string as:

    char strings[] = "hello";
    

    Then that will indeed be null-terminated. When you use quotation marks like that in C, then even though you can't physically see it in the text editor, there is a null terminator at the end of the string.

    There are some C string-related functions that will automatically append a null-terminator. This isn't something the compiler does, but part of the function's specification itself. For example, strncat(), which concatenates one string to another, will add the null terminator at the end.

    However, if one of the strings you use doesn't already have that terminator, then that function will not know where the string ends and you'll end up with garbage values (or a segmentation fault.)

提交回复
热议问题