C++使用 null 部分填充数组
菜鸟问题: 我听说填充字符数组可以用空字符提前终止。这是怎么做到的? 我已经搜索了每一个谷歌结果,但仍然空手而归。
NoobQuestion:
I heard that filling a char array can be terminated early with the null char. How is this done?
I've searched every single google result out there but still have come up empty handed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的意思是这样的:
This 输出 吗
?
Do you mean something like this:
This outputs
?
这是一个称为“空终止字符串”的约定。如果您有一个将其视为字符缓冲区的内存块,并且该缓冲区中有一个空字符,则以空字符结尾的字符串是从缓冲区开头开始一直到(包括空字符)所包含的内容。
这里编译器将在“somestring”后面放置一个空字符(即使您不要求,它也会这样做)。因此,即使缓冲区的长度为 256,所有使用 null 终止字符串的函数(例如
strlen()
)也不会读取超出位置 10 处的 null 字符的内容。这就是“提前终止” - 缓冲区中超出空字符的任何数据都会被任何设计用于处理空终止字符串的代码忽略。最后一部分很重要 - 代码可以很容易地忽略空字符,然后空字符上不会发生“终止”。
That's a convention called "null-terminated string". If you have a block of memory which you treat as a char buffer and there's a null character within that buffer then the null-terminated string is whatever is contained starting with the beginning of the buffer and up to and including the null character.
here the compiler will place a null character after the "somestring" (it does so even if you don't ask to). So even though the buffer is of length 256 all the functions that work with null-terminated strings (like
strlen()
) will not read beyond the null character at position 10.That is the "early termination" - whatever data is in the buffer beyond the null character it is ignored by any code designed to work with null-terminated strings. The last part is important - code could easily ignore the null character and then no "termination" would happen on null character.