Are all char arrays automatically null-terminated?

前端 未结 3 1831
粉色の甜心
粉色の甜心 2020-12-09 05:26

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

相关标签:
3条回答
  • 2020-12-09 05:36

    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.

    0 讨论(0)
  • 2020-12-09 05:46

    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.

    0 讨论(0)
  • 2020-12-09 05:56

    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.

    0 讨论(0)
提交回复
热议问题