Despite the claim that the array notation is nothing more than a thinly disguised form of pointer notation, I have just found out that there is at least a difference, which has taken me half a day to discover:
There is an interesting and important difference between the following declarations which may seem equivalent.
char msg = "Hello";
char *msg = "Hello";
The first declaration reserves an aggregate of 6 characters in the memory space currently being allocated, the data space is initialised to the relevant set of character values. This is only initialisation, the values and hence the text of the string can be altered.
The second declaration reserves enough space to hold a pointer to a character, this pointer is initialised to point to a "secret" system place within your program where the actual character string "Hello" is stored. This is likely to be the same general place that is used for storing layout specification strings used by the printf() and scanf() functions. The value stored in "msg", which is only a pointer to a character, can be altered so it points to a different character. However, and this is encouraged by the ANSI standard, the actual string constant should not be alterable, although this restriction is seldom enforced.
Indeed, under gcc, changing a string declared using the second method produces a compilation warning, and running the executable produces a segmentation fault.
1. Are there any other differences?
2. What is the underlying reasoning behind this difference?
Also, if I have
const char msg = "xxxxxx";
char *p = msg;
I can change msg by *(p+1)='y' for example even though msg is declared as const. At least, gcc does not give a warning.
3. Is there a name for this problem? (i.e. something like alias problem, though I am under the impresion that alias analysis is related to code parallelization.)
4. Is it possible that a good compiler detects this?