Thread: Change one letter from a string

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    27

    Change one letter from a string

    Code:
    #include <stdio.h>
    
    int main() {
       char* string="monkey";
       char* ptr=string;
       *ptr='d';
       puts(string); // Seg fault error
    }
    How to fix this?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,401
    By not doing this:
    Code:
    *ptr='d';


    Basically, you are not allowed to change a string literal. Any attempt to do so results in undefined behaviour.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    Redefine string
    Code:
    char string[]="monkey";

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,866
    Are you trying to make a donkey out of me?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
       char string[]={"monkey"};
       char* ptr=NULL;
       ptr= strchr(string, 'm');
       if(ptr)
           *ptr='d';
    
       puts(string); 
    
       return 0;
    }

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    32
    Quote Originally Posted by gunitinug View Post
    Code:
    #include <stdio.h>
    
    int main() {
       char* string="monkey";
       char* ptr=string;
       *ptr='d';
       puts(string); // Seg fault error
    }
    How to fix this?
    when you intialize a string constant to char pointer, the stringconstant is stored in a text or code (Which is read-only file).

    Code:
     char *string="monkey";
    So, redefine to a char array
    Code:
    char string[]="monkey";
    Understand the difference between string and string constant.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 03-07-2011, 01:24 AM
  2. C random string with letter limitation
    By no4touchy in forum C Programming
    Replies: 6
    Last Post: 10-07-2009, 10:04 PM
  3. counting letter occurences in a string
    By pjr5043 in forum C++ Programming
    Replies: 35
    Last Post: 05-05-2008, 09:18 PM
  4. Remove a letter from a string
    By StarOrbs in forum C++ Programming
    Replies: 6
    Last Post: 04-05-2005, 03:03 PM
  5. checking if a string contains a letter
    By lonbgeach in forum C Programming
    Replies: 2
    Last Post: 04-07-2003, 03:40 PM