C string at the end of '\\0'

那年仲夏 提交于 2019-12-02 06:12:24

On the line char b[10] = "1234567890";, the string literal "1234567890" is exactly 10 characters + 1 null terminator. There is no room left in the array, so it doesn't get null terminated.

Normally, the compiler would warn you for providing an initializer which is too large, but this specific case is a very special pitfall. In the C standard's rules for initialization, we find this little evil rule (C17 6.7.9 §14, emphasis mine):

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

There is no room in your case, so you don't get a null character. And because of this weird little rule, the compiler doesn't warn against it either, because the code conforms to the C standard.

char b[10] = "1234567890"; doesn't contain a NUL-terminator so

while ((*s++ = *t++));

does not terminate correctly (formally the program behaviour is undefined). Note that the constant "1234567890" is a char[11] type; the compiler allows you to assign it to a smaller array, with elements removed automatically.

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