所有 char 数组都自动以空字符结尾吗? [英] Are all char arrays automatically null-terminated?
问题描述
可能我对谷歌搜索太垃圾了,但我一直认为 char 数组只能通过文字初始化 (char 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
声明为 size=2*char 的数组不应该实际获得 2 个字符的大小吗?或者我在这里做错了什么?我的意思是将 char 数组用作简单的 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.
回答你真正的问题:只有字符串文字得到空终止,这意味着 char 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.
这篇关于所有 char 数组都自动以空字符结尾吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!