是否所有字符数组自动空值终止? [英] Are all char arrays automatically null-terminated?
问题描述
也许我只是太转储谷歌上搜索,但我一直以为字符数组只得到空由字面初始化(终止字符X [] =ASDF;
),并得到了当我看到这似乎不是这样有些意外。
Probably I'm just too dump for googling, but I always thought char arrays get only null terminated by an literal initialization (char x[]="asdf";
) and got a bit surprised when I saw that this seems not to be the case.
int main()
{
char x[2];
printf("%d", x[2]);
return 0;
}
输出:0
不应该数组声明大小= 2 *的2个字符大小字符实际获得?还是我做错了什么吗?我的意思是并不鲜见使用一个char数组作为一个简单的字符数组,而不是一个字符串,或者是什么呢?
Shouldn't an array declared as size=2*char actually get the size of 2 chars? Or am I doing something wrong here? I mean it isn't uncommon to use a char array as a simple char array and not as a string, or is it?
推荐答案
您正在访问的范围之外的一个未初始化数组。这是双重的未定义行为的,什么事情都可能发生,甚至还让 0
作为输出。
You are accessing an uninitialized array outside its bounds. That's double undefined behavior, anything could happen, even getting 0
as output.
在回答你的真正问题:只有字符串得到的空值终止的,这意味着字符X [] =ASDF
为 5
元素的数组。
In answer to your real question: Only string literals get null-terminated, and that means that char x[]="asdf"
is an array of 5
elements.
这篇关于是否所有字符数组自动空值终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!