difference between “\\0” and '\\0'

拟墨画扇 提交于 2019-12-04 05:04:39

Double quotes create string literals. So "\0" is a string literal holding the single character '\0', plus a second one as the terminator. It's a silly way to write an empty string ("" is the idiomatic way).

Single quotes are for character literals, so '\0' is an int-sized value representing the character with the encoding value of 0.

Nits in the code:

  • Don't cast the return value of malloc() in C.
  • Don't scale allocations by sizeof (char), that's always 1 so it adds no value.
  • Pointers are not integers, you should compare against NULL typically.
  • The entire structure of the code makes no sense, there's an allocation in a loop but the pointer is thrown away, leaking lots of memory.

They are different.

"\0" is a string literal which has two consecutive 0's and is roughly equivalent to:

const char a[2] = { '\0', '\0' };

'\0' is an int with value 0. You can always 0 wherever you need to use '\0'.

\0 is the null terminator character.

"\0" is the same as {'\0', '\0'}. It is a string written by a confused programmer who doesn't understand that string literals are always null terminated automatically. Correctly written code would have been "".

The line if (str_temp=='\0') is nonsense, it should have been if (str_temp==NULL). Now as it happens, \0 is equivalent to 0, which is a null pointer constant, so the code works, by luck.

Taking strlen of a string where \0 is the first character isn't very meaningful. You will get string length zero.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!