由于某些字符串末尾缺少字符“\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/