字符串没有'\\ 0'字符? [英] Strings without a '\0' char?
问题描述
如果错误,我定义没有'\\ 0'字符数组作为它的最后一个字符,那么什么会发生?
我问这个,因为我发现,如果我试图通过在阵列来迭代(CNT!='\\ 0'),其中CNT是作为索引到一个数组int变量,并同时打印CNT值监测发生了什么迭代的最后一个字符停止2. +额外的字符当然是随机的,但我不能得到它,为什么它停止2.Does后,编译器会自动插入一个'\\ 0'字符?链接到相关的文件将AP preciated。
If by mistake,I define a char array with no '\0' as its last character,what happens then? I'm asking this because I noticed that if I try to iterate through the array while(cnt!='\0'),where cnt is a int variable used as an index to the array,and simultaneously print the cnt values to monitor what's happening the iteration stops at the last character +2.The extra characters are of course random but I can't get it why it has to stop after 2.Does the compiler automatically inserts a '\0' character?Links to relevant documentation would be appreciated.
要弄清楚我举一个example.Let的说,数组STR包含单词DOH(没有'\\ 0')。在每个循环打印CNT变量会给我这个
卫生署+
或卫生署^
等
To make it clear I give an example.Let's say that the array "str" contains the word doh(with no '\0').Printing the cnt variable at every loop would give me this doh+ or doh^ and so on.
推荐答案
修改(未定义行为)
访问数组边界之外的数组元素是不确定的行为。结果
调用字符串函数比C字符串的任何其他未定义行为。结果
不这样做!
Accessing array elements outside of the array boundaries is undefined behaviour.
Calling string functions with anything other than a C string is undefined behaviour.
Don't do it!
的 C字符串是,并包括 '\\ 0'
(NUL终止)终止字节序列。所有字节必须属于同一对象的
A C string is a sequence of bytes terminated by and including a '\0'
(NUL terminator). All the bytes must belong to the same object.
总之,你看到的是一个巧合!
Anyway, what you see is a coincidence!
但它也可能发生这样的
,------------------ garbage
| ,---------------- str[cnt] (when cnt == 4, no bounds-checking)
memory ----> [...|d|o|h|*|0|0|0|4|...]
| | \_____/ -------- cnt (big-endian, properly 4-byte aligned)
\___/ ------------------ str
这篇关于字符串没有'\\ 0'字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!