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

后端 未结 6 1903
爱一瞬间的悲伤
爱一瞬间的悲伤 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:01

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

    Let's find out:

    int main() {
      char str[] = "Hello\0";
      int length = sizeof str / sizeof str[0];
      // "sizeof array" is the bytes for the whole array (must use a real array, not
      // a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
      // to get the number of items in the array
      printf("array length: %d\n", length);
      printf("last 3 bytes: %02x %02x %02x\n",
             str[length - 3], str[length - 2], str[length - 1]);
      return 0;
    }
    

提交回复
热议问题