C++使用 null 部分填充数组

发布于 2024-09-28 05:51:00 字数 65 浏览 1 评论 0原文

菜鸟问题: 我听说填充字符数组可以用空字符提前终止。这是怎么做到的? 我已经搜索了每一个谷歌结果,但仍然空手而归。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

℉絮湮 2024-10-05 05:51:00

您的意思是这样的:

    char test[11] = "helloworld";
std::cout << test << std::endl;
test[2] = 0;
std::cout << test;

This 输出 吗

helloworld
he

Do you mean something like this:

    char test[11] = "helloworld";
std::cout << test << std::endl;
test[2] = 0;
std::cout << test;

This outputs

helloworld
he

?

遇到 2024-10-05 05:51:00

这是一个称为“空终止字符串”的约定。如果您有一个将其视为字符缓冲区的内存块,并且该缓冲区中有一个空字符,则以空字符结尾的字符串是从缓冲区开头开始一直到(包括空字符)所包含的内容。

const int bufferLength = 256;
char buffer[bufferLength] = "somestring"; //10 character plus a null character put by the compiler - total 11 characters

这里编译器将在“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.

const int bufferLength = 256;
char buffer[bufferLength] = "somestring"; //10 character plus a null character put by the compiler - total 11 characters

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文