Eric Sosman <es*****@acm-dot-org.invalidwrites:
Keith Thompson wrote:
[...]
>More pedantically, if you have an array whose initializer is a string
literal, it's a good idea to declare the array as const.
Wouldn't that depend on the purpose of the array?
[snip]
Yes, sorry, I goofed.
If you have a *pointer* whose initializer is a string literal, you
should declare it as const:
const char *p = "hello";
If you have an *array*, declare it as const or not depending on how
you want to use it; the initializer is irrelevant:
char arr[] = "hello";
Here, the string literal is (logically) *copied* to the array. In the
first case, the pointer actually points to the string literal itself.
More precisely, the string literal causes an anonymous array of static
storage duration, just large enough to hold the sequence of
characters, to be created. The pointer points to this array. Any
attempt to modify the array invokes UB.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.