问题
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