0

where is the change occurring if i am reassigning a character to *p .

#include<stdio.h>
int main()
{

char* p="hello" ;
printf("%s",p);
*p='a' ;
printf("%s",p);

return 0;

}

*p='a' should have replaced 'h' with 'a' in the string .

*p should access and base element of the string pointed by p and replace it .

but print statement prints "hello " both times

but it doesnt can anyone explain why not ??

Elijah
  • 306
  • 1
  • 12

2 Answers2

3

This:

*p='a' ;

Is illegal, because p points to a literal string. Unfortunately C allows you to store the address of a literal string in a non-const pointer without any cast or warning, for historical reasons. But really, you should do this:

const char* p="hello" ;

Then your compiler will reject this program, because it is not valid to modify literal strings.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • yes it will reject program if i pur const qualifier in front of it .But what i am not getting is ok "hello" string is put into anonymous location in memory and p is pointing to it and am able to print *p ie first character then why i cant replace it ? – Elijah Sep 14 '14 at 11:43
  • 2
    @rohitgoel: because the compiler is allowed to use read-only memory for literal strings. Modifying it is undefined behavior, so anything could happen (or nothing, as in your case). – John Zwinck Sep 14 '14 at 12:09
0
char* p="hello" ;

will place hello in the read-only parts of the memory and making p a pointer to that, making any writing operation on this memory illegal.

It has no name and has static storage duration (meaning that it lives for the entire life of the program); and a variable of type pointer-to-char, called p, which is initialised with the location of the first character in that unnamed, read-only array.

So

*p='a' ;

it will result in a memory access violation.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • then how come p="bye" works if it is written on read only memory? – Elijah Sep 14 '14 at 11:41
  • 1
    @rohitgoel `p="bye";` this is re-assignment of pointer to new string not modifying pointer. while `*p='a'` is try to replace first character of string pointed by pointer with `a`. – Jayesh Bhoi Sep 14 '14 at 11:47
  • ok i got it , but then if its on read only memory and i am trying to write on that location why compiler doesnt show me any error ? when *p=a is executed something should be happening if no error is popping up right ? – Elijah Sep 14 '14 at 11:51
  • @rohitgoel For that you have take care manually by using `const` keyword.It will give you error at compile time using `const`. – Jayesh Bhoi Sep 14 '14 at 11:53
  • 2
    @rohitgoel "_when *p=a is executed something should be happening_" I tried with my VS. In `Debug` mode it crashes, and in `Release` it does not seem to create any assembly code for this assignment. So it "does not exist" after optimization. Of course, do not rely on any assumptions like this. The behavior is undefined. – AlexD Sep 14 '14 at 12:02