modifying the char*

hi everyone here is the code
   char* a = "aaa";
   *a++ = 'd'; // run time error occurs but no compiler error!! 

could you describe why i can't change the value of a?? and if i can how?

Last edited on
String literals are constant, you cannot change them. The compiler should give you a warning on the first line.
This is the correct variant:

string a="aaa";
String literals are stored in a read-only data segment of the binary. So the runtime error is because you're trying to change something you aren't supposed to.

There's no compiler error as you are, unfortunately, allowed to assign a non-const char* to point at a literal to support legacy code. Ideally your compiler should warn you about this!

To avoid the probem, store your string in a buffer.

char buffer[16] = "aaa"; // copy "aaa" into a buffer of 16 chars
char* a = buffer;
*a++ = 'd'; 


PS Is you code in a .cpp file?
Last edited on
thank you, but i'm going to push it little further,
you said that it's a constant ok i get it. is there anyway to break it constness
such as cons_cast, if we can't could you describe it??

thank you!!

thank you andy for the information then i mark it solved!!

PS yes it is a .cpp file :)
Last edited on
is there anyway to break it constness

No. But you can copy it, which is what string does.
i get it now..

thank you again guys!! i'll mark it solved
Topic archived. No new replies allowed.