Quote:Original post by xeddiex
If it's like you say Quote: Way Walker
"I believe string literals are "const char *" in C++ and "char *" in C, but the behavior of modifying a string literal is undefined in both cases. What does this mean? Anything can happen when you try to modify it. In your case, this meant it crashed the program (it was in read only memory)."
...then, char array[] = "doggie" would be a const string literal too!? If so, then why am I able to change a value of a element of a const string ie. array[3] = 'x'; (string is now, dogxie) /*NO CRASH*/ But can't do that with "char *str = "doggie" then, str[3] = 'x'; /*CRASH*/
In dimensionX's example, you have str with type "char *" which is pointing to a string literal which you should think of as having type "const char *". Modifying something that is const qualified usually produces undefined behavior, even if it's through a non-const pointer.
And I don't think you understood what I was saying, so my appologies for not being clear.
char myStr[] = "doggie";
is the same as doing
char myStr[7] = "doggie";
which means that myStr is an array of 7 elements in both cases. Doing
myStr[3] = 'x';
will change myStr to "dogxie" in both cases. However,
char *myStr = "doggie"; myStr[3] = 'x';
produces undefined behavior because you're modifying the string literal (in your case, this means it crashes).
Hmm... perhaps what's confusing you is the difference between [] when declaring a variable and [] in a prototype list? Consider:
void function1(char arg1[]) {}void function2(char arg2[7]) {}void function3(char *arg3) {}int main(void) { char var1[] = "doggie"; char var2[7] = "doggie"; char *var3 = "doggie"; return 0;}
EDIT: arg1 is a pointer to char, arg2 is a pointer to char, arg3 is a pointer to char.
var1 is an array of 7 char, var2 is an array of 7 char, var3 is a pointer to char.
[Edited by - Way Walker on December 2, 2004 2:09:29 PM]