Are all char arrays automatically null-terminated?

安稳与你 提交于 2019-11-28 08:40:42

You are accessing an uninitialized array outside its bounds. That's double undefined behavior, anything could happen, even getting 0 as output.

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 arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal";, and some string char pointers returned from stdlib string methods.

C does no bounds checking. So an array declared as size 2*char gives you 2 memory slots that you can use, but you have the freedom to walk all over the memory on either side of that, reading and writing and thereby invoking undefined behavior. You may see 0 bytes there. You may write to array[-1] and crash your program. It is your responsibility to keep track of the size of your array and avoid touching memory that you didn't allocate.

It is common to use a char array as a simple char array, i.e. other than a C string, for instance, to hold any arbitrary buffer of raw bytes.

If t is an array of size 2, then the last case is t[2 - 1] = t[1] and not 2. t[2] is out of bounds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!