String literals and pointers

Do you know how to access c-style literal strings? Try this two-part quiz and see if you are able to unravel the different semantics of character pointers and arrays.


a) What is wrong, if anything, with the following code?

b) How do these 2 lines of code differ?


a) Since a literal string decays to a pointer type of char const * and NOT char * this is not strictly speaking legal C++; however, to maintain backwards compatibility with C, compilers will allow this but they (should) produce a warning since this construct is now deprecated in C++ and will be removed from future versions of the standard.

b) Line one is a pointer to a literal string, which is immutable and attempting to modify the string will result in undefined behaviour. Line two is an array that is initialised with a string value, which means you are allowed to remove the const specifier and modify the array if you so wish (since you own the memory that represents the array).