1

I was looking at tutorials for C and pointers on the internet and found a debugging example and am wondering how to fix this block of code? I have been looking for a while and can't find out how to make it work. I want to replace the 'i' in "Harris" with an "a".

char * ptr = (char *) "Harris";

ptr[4]="a";
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 1
    String Literals CANNOT be modified (except on ancient hardware not relevant here) You can use a *compound literal* `char *ptr = (char[]){ "Harris" };` (C99+) – David C. Rankin Mar 20 '19 at 00:17

2 Answers2

3

While you can assign a constant to a char pointer, you can't normally write to it. Fix your code:

char ptr []= "Harris";

For not-your-legacy code use -fwritable-strings.

Joshua
  • 40,822
  • 8
  • 72
  • 132
2

ptr[4]='a';

Single quotes for character constants.

shrewmouse
  • 5,338
  • 3
  • 38
  • 43