用C空字节和数组 [英] Null byte and arrays in C
问题描述
如果我宣布的字符数组说10个字符,像这样......
If I declare a char array of say 10 chars like so...
char letters[10];
我在创建一组的内存位置重新psented从那么指数0-9个字符$ P $ 10日指数是空字节?
am I creating a set of memory locations that are represented as chars from index 0-9 then the 10th index is the null byte?
如果这是否意味着我真的在内存中创建11个地点为数组(0至10)的最后一个元素是空字节还是我在存储器(0〜9)10个地点则C加在新的位置空字节(所以数组是1个字节的时间比我申报)?
if so does that mean I'm really creating 11 locations in memory for the array (0 to 10) with the last element being the null byte or do I have 10 locations in memory (0 to 9) then C adds the null byte at a new position (so the array is 1 byte longer than I declared)?
感谢
推荐答案
好像你用数组和字符串混淆。结果
当你声明
Seems like you are confused with arrays and strings.
When you declare
char letters[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
然后它保留仅仅10中的存储器位置连续字节。
then it reserves only 10 contiguous bytes in a memory location.
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 //memory addresses. I assumed it is to be starting from 200 for simplification.
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| | | | | | | | | | |
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
| | | | | | | | | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
在C索引从 0
启动。您可以从字母访问分配的内存位置[0]
到信[9]
。访问位置信[10]
将调用的未定义行为即可。但是,当你声明这样
In C indexing starts from 0
. You can access your allocated memory location from letters[0]
to letters[9]
. Accessing the location letters[10]
will invoke undefined behavior. But when you declare like this
char *letters = "0123456789";
或
char letters[11] = 0123456789";
再有空间的11字节的内存分配; 10 0123456789
和一个 \\ 0
(NUL字符)。
then there are 11 bytes of space are allocated in memory; 10 for 0123456789
and one for \0
(NUL character).
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 //memory addresses. I assumed it is to be starting from 200 for simplification.
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
| | | | | | | | | | | |
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '\0' |
| | | | | | | | | | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
^
| NUL character
再举一个例子
#include <stdio.h>
int main(){
char arr[11];
scanf("%s", arr);
printf("%s", arr);
return 0;
}
输入:
asdf
输出:
asdf
现在对内存位置看看
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
| | | | | | | | | | | |
| 'a' | 's' | 'd' | 'f' |'\0' | | | | | | |
| | | | | | | | | | | |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+
这篇关于用C空字节和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!