0

I have written a code like below

char *p = "Pointers";
p[2] = 'z';
printf ("%d\n",p);

This gives me erro. Can anyone explain me what is this.

Abhishek
  • 650
  • 1
  • 8
  • 31
  • 2
    1) You are not allowed to modify a string literal. 2) `p` is a pointer, so format string must be `%p`. – Jean-Baptiste Yunès Jun 22 '17 at 15:21
  • Short answer: `char *p = "Pointers";`-> `char p[] = "Pointers";` – Jabberwocky Jun 22 '17 at 15:22
  • I believe the error has the message explaining itself. – Eugene Sh. Jun 22 '17 at 15:22
  • As @EugeneSh. mentions, it has to be possible to determine the problem from the error message. Please post such message if you don't understand it. – Iharob Al Asimi Jun 22 '17 at 15:26
  • when i wrote char *p = "Pointers"; and then p[2] = 'z'. It gives me error. But when i wrote char p[]="Pointers" and then p[2] = 'z'. It does not give me error. Why – Abhishek Jun 22 '17 at 15:36
  • The result of trying to change the string literal is undefined behavior. – BLUEPIXY Jun 22 '17 at 15:48
  • 2
    @Abhishek The first version is pointing a pointer to char to a string literal, which is likely allocated in read-only memory somewhere in the program. Thus, when you try to alter that memory through 'p' it causes the program to error out. The second version allocates an array of characters, named p, on the stack that has the same size as the string literal "Pointers" and is initialized by it. From there, you are free to alter the contents of that array of characters to your heart's content (so long as you stay in the bounds of the array). – jschultz410 Jun 22 '17 at 15:48
  • @Jean-BaptisteYunès Your point (2) is not quite correct. The format string `%d` is certainly wrong, but since `p` is a pointer to char, `%s` would be fine. – Steve Summit Jun 22 '17 at 16:54
  • @SteveSummit right, depending on what OP wants. Most probably `%s`. – Jean-Baptiste Yunès Jun 23 '17 at 06:29

0 Answers0