Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Simple pointer question (http://www.go4expert.com/forums/simple-pointer-question-t3458/)

tedman 18Mar2007 03:44

Simple pointer question

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 18Mar2007 03:50

Re: Simple pointer question
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 18Mar2007 10:13

Re: Simple pointer question
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.

All times are GMT +5.5. The time now is 01:57.