C 字符串末尾的空字符是否始终为常量且无法修改?意思是,程序员可以修改 C 字符串末尾的空字符 /0 吗?或者它是恒定的并且不能被移除。示例:'Steak' 在 cstring 中,它在位置 5 处有 \0。当 'steak' 被修改时,我们可以完全删除 \0 吗?
2 回答
C 字符串末尾的空字符是否始终为常量且无法修改?
如果我们谈论的是字符数组(静态或动态),则否,但如果您指的是常量字符串文字,则可以,例如:
const char* str = "steak";
程序员可以修改 C 字符串末尾的空字符 /0 吗?
是的,只要内存不是只读的。
我们可以完全删除 \0 吗?
是的。但是,如果您将此字符串与期望的函数一起使用'\0'
,则行为未定义
If the C-string is the return value of the c_str()
or data()
member functions of std::string
, then the standard forbids the modification of the trailing 0
element. Of course, just because the standard forbids it doesn't mean that anything in C++ or its runtime environment will warn you about the violation. It's quite possible that you can write code which attempts to modify the trailing 0
, and it will execute without raising any alarms. However, it is also very likely that things will go wrong in unpredictably strange ways.
So don't do it.