C语言 在 C 中将字符串设置为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5608179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting a string to null in C
提问by gegardmoussasi
Is setting 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?
将字符串设置为 '\0' 是否与在其他语言中将字符串设置为 NULL 相同?或者...将字符串设置为 '\0' 是否意味着该字符串只是空的?
char* str = 'char *str;
/* ... allocate storage for str here ... */
*str = 'char* str = NULL;
'; /* Same as *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.
我有不同的函数可用于空字符串和空字符串,所以我不想意外地在空字符串上调用我的空字符串函数之一。
回答by Jens
Your line char *str = '\0';actually DOESset 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 :-)
您的行char *str = '\0';实际上确实将 str 设置为(相当于)NULL。这是因为'\0'在 C 中是一个值为 0 的整数,这是一个有效的空指针常量。虽然它非常模糊:-)
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 twozero bytes).
制备str(指针)一个空字符串与完成str = "";(或str = "\0";,这将使STR指向的数组2零个字节)。
Note: do not confuse your declaration with the statement in line 3 here
注意:不要将您的声明与此处第 3 行中的声明混淆
##代码##which does something entirely different: it sets the first character of the string that strpoints to to a zero byte, effectively making strpoint to the empty string.
它做了一些完全不同的事情:它将字符串的第一个字符设置str为一个零字节,有效地str指向空字符串。
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 :-)
术语吹毛求疵:字符串不能设置为 NULL;C 字符串是在某处具有 NUL 字符的字符数组。没有 NUL 字符,它只是一个字符数组,不能传递给需要(指向)字符串的函数。然而,指针是 C 中唯一可以为 NULL 的对象。并且不要将 NULL 宏与 NUL 字符混淆:-)
回答by Chris Eberle
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:
不,在这种情况下,您指向的是一个长度为 0 的真实(非空)字符串。您只需执行以下操作即可将其设置为实际空值:
##代码##
