-1
#include<stdio.h>
void main()
{
char d;
char *r="Helloo";
printf("%s\n",r);

d=*(r+1);
printf("%c",d);

*(r+0)=d;

printf("%s\n",r);

}

this was working fine when i stored the string in a character array but why doesn't it work now

skayp
  • 33
  • 6

1 Answers1

2
char *r="Helloo";

You assigned pointer r to a string literal. String literals should be treated as immutable. Any attempt to modify one leads to undefined behavior (N1570, Section 6.4.5/7).

With

char r[]="Helloo";

You have the string stored in an array that you can modify so it works as expected.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
iBug
  • 35,554
  • 7
  • 89
  • 134
  • Are C string laterals *necessarily* immutable, or is that implementation dependant? – Scott Hunter Sep 16 '18 at 12:06
  • @ScottHunter It depends on the implementation. The standard only says modifying string literals has undefined behavior, so portable code must treat them as immutable. But then that's what *immutable* means in general: You try to modify it, you get UB. – melpomene Sep 16 '18 at 12:08
  • OK, but dictionary definition of *immutable* makes it sound like the string *can't* be modified, even if you tried (which is the behavior that led to the question), whereas the "C" definition sounds like there are no guarantees as to what happens if you try. A distinction the person asking the question might not be aware of (and might not even care). – Scott Hunter Sep 16 '18 at 12:54
  • @ScottHunter Yeah I understand that. Jonathan's edit makes this clear. (thanks Jonathan!) – iBug Sep 16 '18 at 13:08