2

I am attempting to manipulate individual characters in a string, in this case change 4th 'a' to a 'b'.

string password = "aaaaa";
printf("password: %s\n",password);

int j = 'b';
password[3] = (char) j;
printf("password: %s\n",password);

this returns:

password: aaaaa

Segmentation fault

One last note: in the first line I declare 'string' like a variable. This contrivance is allowed by the CS50 library - It should work and I have used it in the past.

Thank you in advance.

Tikhon
  • 451
  • 1
  • 5
  • 13
  • 1
    Thank you for your comments - I now updated the tag. Yes I am doing the excellent cs50 and have included #include – Tikhon Dec 16 '18 at 05:16

1 Answers1

4

"aaaaa"; is a String Literal which is immutable on most systems, so password[3] = (char) j; attempts of modify an immutable object resulting in a SegFault.

Instead,

char password[] = "aaaaa";

Presuming your "string" is a typedef of char* using a compound literal allows the same result, e.g.:

string password = (char[]){"aaaaa"};
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85