Is setting 开发者_StackOverflow中文版a string to '\0' the same thing as setting a string to NULL in other languages? Or... does setting a string to '\0' mean that the string is simply just empty?
char* str = '\0'
I have different functions to use for null strings and empty strings, so I don't want to accidentally call one of my empty string functions on a null string.
Your line char *str = '\0';
actually DOES set str to (the equivalent of) NULL. This is because '\0'
in C is an integer with value 0, which is a valid null pointer constant. It's extremely obfuscated though :-)
Making str
(a pointer to) an empty string is done with str = "";
(or with str = "\0";
, which will make str point to an array of two zero bytes).
Note: do not confuse your declaration with the statement in line 3 here
char *str;
/* ... allocate storage for str here ... */
*str = '\0'; /* Same as *str = 0; */
which does something entirely different: it sets the first character of the string that str
points to to a zero byte, effectively making str
point to the empty string.
Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be NULL. And don't confuse the NULL macro with the NUL character :-)
No, in this case you're pointing to a real (non-null) string with a length of 0. You can simply do the following to set it to actual null:
char* str = NULL;
精彩评论