c - *以双 '\0' 结尾的字符

标签 c c-strings null-terminated nul

由于某些字符串末尾缺少字符“\0”,我的代码崩溃了。

我很清楚为什么我们必须使用这个终止字符。我的问题是, 向字符数组添加潜在的第二个空字符是否存在问题 - 以解决字符串问题?

我认为向每个字符串添加一个 '\0' 比验证它是否需要然后添加它更便宜,但我不知道这是否是一件好事。

最佳答案

is there a problem to have this char ('\0') twice at the end of a string?

这个问题不够明确,因为“字符串”对人们来说意味着不同的东西。
让我们使用 C 规范定义,因为这是一篇 C 文章。

A string is a contiguous sequence of characters terminated by and including the first null character. C11 §7.1.1 1

所以 string 不能有 2 个 null 字符,因为字符串在到达第一个字符时结束。 @Michael Walz

相反,重新解析为“向字符数组添加潜在的第二个空字符是否存在问题 - 以解决字符串问题?”


尝试向字符串添加空字符的问题是混淆。 str...() 函数使用上面定义的 C 字符串。

// If str1 was not a string, strcpy(str1, anything) would be undefined behavior.
strcpy(str1, "\0");  // no change to str1

char str2[] = "abc";
str2[strlen(str2)] = '\0'; // OK but only, re-assigns the \0 to a \0
// attempt to add another \0
str2[strlen(str2)+1] = '\0'; // Bad: assigning outside `str2[]` as the array is too small

char str3[10] = "abc";
str3[strlen(str3)+1] = '\0'; // OK, in this case
puts(str3);                  // Adding that \0 served no purpose

正如许多人评论的那样,添加一个备用的 '\0' 并不能直接解决代码的根本问题。 @Haris @Malcolm McLean

未发布的代码才是真正需要解决的问题 @Yunnosch ,而不是尝试附加第二个 '\0'

关于c - *以双 '\0' 结尾的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44460652/

相关文章:

c - 霍夫曼编码、保存代码和用 C 编写二进制文件

c - 在 "C"程序中,如何将十六进制值存储在字符串变量中?

c++ - 将 cstring 转换为驼峰式

java - 在 Java 中过滤命令行输入中的符号

arrays - 何时/为什么需要 '\0' 来标记 (char) 数组的结尾?

头文件中的代码似乎会导致编译错误

c - 用C处理 "JACK audio"数据?

c++ - 比较 std::string 和 C 样式字符串文字

c - fprintf 字符串终止的心理障碍

c++ - 如何正确地将 char* 转换为 std::string? (使用 expat/std::string(char*) 时的问题)