Why does C++ need array of 6 size to store 5 letter word whereas C allows just 5?

ε祈祈猫儿з 提交于 2021-01-27 20:33:58

问题


I have tried this following statement in C and C++.

char A[5] = {"Hello"};

While C accepts this, C++ is throwing an error saying the string is too long. If there is a null character to be added, why is it accepted in C but not in C++?


回答1:


Please note that char A[5]={"Hello"}; is a bug in either language. There must be room to allocate the null terminator.

It compiles in C because the language 6.7.9/14 has an an odd special rule/language bug, 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.

This allows a character array to be initialized with a string literal which has exactly the same amount of characters as the size of the array, but silently discard the null termination.

C++ fixed this dangerous language bug.



来源:https://stackoverflow.com/questions/58428098/why-does-c-need-array-of-6-size-to-store-5-letter-word-whereas-c-allows-just-5

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