Simple pointer question

tedman's Avatar, Join Date: Jan 2007
Go4Expert Member
main() {

char *s = "IDIOT";
char *start, *end;
start = s;
end = s+strlen(s)-1;
printf("%c, %c",*start, *end);      // prints   I   T
*start = *end;                            // crashing at this point
printf("%c, %c",*start, *end);     // should print T   T

What I'm trying to do above is just replace I with T and I'm getting a segmentation fault!!! am clueless, please can someone help!!!
DaWei's Avatar, Join Date: Dec 2006
Team Leader
In many modern OSs a string generated such as you have generated it lies in protected memory space. That means you can read it, but not write it. You can put it in local, writable space, if you like:
char writableString [] = "IDIOT";
char *start = writableString;
...etc., etc.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
DaWei, good answer. Probably thats the main reason some modern languages like C# and java have 2 types of string the editable and the one that is not editable. I always wondered why they have such things and the main reason might lie in this thread.