سؤال

I have the following code:

void uppercase(char *sir)
{

for(int i=0;i<strlen(sir);i++)
{

 sir[i]=(char)toupper(sir[i]);
}
} 


int _tmain(int argc, _TCHAR* argv[])
{

//char  lower[]="u forgot the funny"; this works
//char  *lower="u forgot the funny";  this gives me a runtime error

uppercase(lower);

cout<<lower<<"\n\n";

system("PAUSE");

return 0;
}

I have noted that if I run with the char vector it works. When I try to run with the second method it generates a runtime error. I would like to know the reason for this behaviour please.

هل كانت مفيدة؟

المحلول

You cannot modify string literals; doing so (as in your second case) is undefined behaviour.

char x[] = "foo";

creates a character array containing the characters f,o,o,\0. It's basically a mutable copy of the string.

char *x = "foo";

creates a string pointer pointing to the "foo" string literal. The literal may live in some read-only memory, in the program memory, or in a constant pool. Writing to it is undefined behaviour. Also, not that the type of a string literal is always const char[], so assigning it to a char * is violating const-correctness.

نصائح أخرى

The former creates a character array which can be mutated, the latter is a pointer to fixed memory (which cannot be manipulated)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top