string increment(string s, int loc) {
  char c = s[loc];
  c += 1;
  s[loc] = c;
  return s;

increment("A", 0); returns Segmentation fault at s[loc]=c;and I have no idea why.

Is there a specific function to replace a character?

Edit to further simplify:

string a="ABC";
a[1]= 'D'; //returns Segmentation fault
a[0]=a[1]; //returns Segmentation fault

It is as if strings are 'read-only'

  • Are you sure that loc is less than strlen(s)? You might try printing out your parameters as the first line of the function.
    – Cliff B
    May 17 '17 at 17:03
  • After line 1, c = 'A'. and after line two, c='B'. Therefore, line one was able to collect char 'A' from string "A" at loc=0 and increment it to 'B' successfully. My assumption is I could then put c back into s at the same location loc=0.
    – circlemaze
    May 17 '17 at 17:12

String literals are read only! This declaration string a="ABC"; makes a a string literal, which is stored in read-only memory.

  • Is there a way to define a string such that it can be modified like a typical array? Or do I have to create 3 string pieces from the original and concatenate together to modify a character in the middle
    – circlemaze
    May 17 '17 at 22:55

My workaround for this is as follows:

string a = "ABC";
char c[5] = {'A', '\0', '\0', '\0', '\0'};
printf("%s\n", c); //Prints AB

An array of char declared using this method can be edited directly using chars even when they are from other sources like strings. I still do not understand why c is an editable array but a is not.

  • a is not "an editable array" because it is a string literal (aka constant). Here is more technical information. Or internet search "c string literal" May 19 '17 at 12:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .