0

I am trying to take change a single character in the pointer array I have declared, but I get a seg fault every time. This is what I am trying to do:

void manip(char * bits)
{
  bits[3] = 'a';
}


int main() {
  char * bits;
  bits = "testtesttest";
  manip(bits);
  printf("%s", bits);
  return 0;
}

What am I doing wrong?

aons32
  • 25
  • 3
  • 1
    `bits` is a pointer to a string literal, you can't change those. – anastaciu Sep 17 '20 at 19:56
  • If you want to change the string, you need to make a writable copy: `char bits[]="testtesttest";` When you declare `bits` as an array without specifying the size, the compiler will create an array of the appropriate size (13 chars in this case), and copy the string literal (and the NUL terminator) into the array. Then you can modify the string. – user3386109 Sep 17 '20 at 19:59
  • @user3386109 that doesn't work, it says I need to include a size of the string. – aons32 Sep 17 '20 at 20:13
  • String constants are immutable. You cannot change them. https://stackoverflow.com/questions/7547821/changing-one-char-in-a-c-string – user10191234 Sep 17 '20 at 22:56

0 Answers0