What does the symbol \0 mean in a string-literal?

后端 未结 6 1849
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 12:26

Consider following code:

char str[] = \"Hello\\0\";

What is the length of str array, and with how much 0s it is ending?

6条回答
  •  眼角桃花
    2020-11-27 13:03

    char str[]= "Hello\0";
    

    That would be 7 bytes.

    In memory it'd be:

    48 65 6C 6C 6F 00 00
    H  e  l  l  o  \0 \0
    

    Edit:

    • What does the \0 symbol mean in a C string?
      It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

    • What is the length of str array? (Answered before the edit part)
      7

    • and with how much 0s it is ending?
      You array has two "spaces" with zero; str[5]=str[6]='\0'=0

    Extra example:
    Let's assume you have a function that prints the content of that text array. You could define it as:

    char str[40];
    

    Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

    54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
    69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00
    

    So you print that char array. And then you want a new message. Let's say just "Hello"

    48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
    69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00
    

    Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

提交回复
热议问题