-2

My code is like this

Char * q = "Bye";
strcpy (&q[1], "K");

When I compile it, it starts hanging. I am using in MinGW in Windows 7. Even if I allocate malloc to q, the problem persists

If i try to assign q[1]= 'K', then also it hangs

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
SouthArcot
  • 21
  • 1
  • 3
  • 3
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Nate Eldredge Dec 12 '15 at 03:18
  • 1
    The code hangs at compilation? – nicomp Dec 12 '15 at 03:22
  • You're not trying to change the contents of a `char*`. If you were, it would be `q = something;`. You're actually trying to change the contents of the thing it points to. – user253751 Dec 12 '15 at 03:50
  • 1
    But your code won't even compile! – Spikatrix Dec 12 '15 at 08:34

1 Answers1

1

When you initialize a char pointer with a string literal the compiler may store the string in read-only memory. If you really want to have the string be modifiable then try storing it on the local stack:

Char q[]="Bye";
Turn
  • 6,656
  • 32
  • 41