In article <11**********************@m79g2000cwm.googlegroups .com>,
<sh********@gmail.comwrote:
>void foo(char str[])
{
char strA[] = "Hello";
strA[0] = strA[0];
str[0] = str[0];
}
>void main()
void is not one of the return types for main() which must be supported,
though it is allowed for a particular implementation to support
additional declarations for main() . Your code compiled this time;
in the next compiler release it might not.
>{
foo("abcd");
}
>Line:
str[0] = str[0]; throws an exception
whereas strA[0] = strA[0]; works fine.
Why?
This is undoubtedly in the C FAQ.
char strA[] = "Hello";
creates a char array of length 6 and initiazes it with the
characters 'H', 'e', 'l', 'l', 'o', and '\0'.
This array is writable, with the characters given in the string
considered to be just initial values -- it is short-hand for
using a list of char in the initializer.
foo("abcd");
passes to foo the address of a literal string that contains
"abcd\0" . It is the pointer that is passed, not the individual
characters. C implementations are allowed to put all literal
strings of this type into read-only memory.
If you were to change your foo() to use
char *strA = "Hello";
then you would find the same exception behaviour for it, as
in that case too what is stored is the pointer to the
literal string that is allowed to be read-only.
As a quick summary: if a given double-quoted string is acting
as a pointer to storage, then the string should be assumed to
be read-only; but if the given double-quoted string is in a declaration
to show what characters to put into something marked as a character array,
then the resulting character array is writable.
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer