1

Possible Duplicate:
Is it possible to modify a string of char in C?

char *s = "anusha";

Is this like a constant pointer? When i tried to change the character in location 3 by writing s[3]='k', it gave me a segmentation fault. So i am assuming it is like pointing to a constant array or s is a constant pointer? Which among the two? Please clarify.

Community
  • 1
  • 1
Anusha Pachunuri
  • 1,389
  • 4
  • 18
  • 39

2 Answers2

4

That is correct, you are not allowed to modify string literals.

However, it's legal to do this:

char s[] = "anusha";
s[3] = 'k'

The difference here being that it is stored as a local array that can be modified.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
0

It looks like your compiler treats "anusha" as a pointer to char, but places the string itself into write-protected memory. I remember reading that this is a convenience policy in order to comply with existing code.

As Joe pointed out, this is detailed in Is it possible to modify a string of char in C?.

Community
  • 1
  • 1
krlmlr
  • 25,056
  • 14
  • 120
  • 217
  • Here's a practical reason: Any time "anusha" appears as a literal, the compiler can just use the same address. This won't be valid if it is allowed to be changed. – Michael Chinen Feb 04 '12 at 02:48
  • @Michael So as i read in another similar post...... if i said char *s="anusha"; and printf("anusha"); later somewhere in the code, the compiler uses the same string literal address in both the statements? Does that mean it checks if such a string literal already exists? – Anusha Pachunuri Feb 04 '12 at 02:53
  • That's a reason for write-protecting it, but not for making it `char*` instead of `const char*`. – krlmlr Feb 04 '12 at 02:53
  • 2
    Ah, I see what you are saying now. And I didn't know that. Interestingly, apparently in c it is char[], (not char*), and in c++ the type is const char*. The reason for char[] instead of char* is that sizeof will give you the size of the string this way. – Michael Chinen Feb 04 '12 at 03:02