1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Simple pointer question

Discussion in 'C' started by tedman, Mar 17, 2007.

  1. tedman

    tedman New Member

    Joined:
    Jan 28, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    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!!!
     
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    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:
    Code:
    char writableString [] = "IDIOT";
    char *start = writableString;
    ...etc., etc.
    
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    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.
     

Share This Page