1

Suppose I have this in C++:

char *p = "Apple";

I can't do this:

p[1] = 'w';

But why can I do this?

p = "OrangeTorange";
user1343318
  • 2,093
  • 6
  • 32
  • 59
  • There is about 100 of these on here already. I'll be back with a definite duplicate. – Mats Petersson Aug 15 '13 at 17:39
  • 2
    @MatsPetersson: That is not a duplicate. He clearly knows that he cannot write to the literal, but he is asking if he can point to a different literal (although he might not know that he is asking it). Not sure why -3 here... the user might not know what the difference is, but the question is proper. – David Rodríguez - dribeas Aug 15 '13 at 17:48
  • 1
    Thanks David. @Mats, I actually google-d and checked stackoverflow before asking. I understand that related questions were asked but I couldn't find which exactly answered this. – user1343318 Aug 15 '13 at 17:59

3 Answers3

3

As p points to constant string literal so if you do: p[1] = 'w'; then you are trying to modifying string literal that is read only constant and its illegal operation (Undefined behavior).

Whereas in expression p = "OrangeTorange"; you modify value of p variable that is pointer to a char. And assigning new address value to p is a valid operation, now p start pointing to new string literal.

To add further, Suppose if p points an array then p[1] = 'w'; is not a invalid operation consider below example code:

char str[] = "Apple";
char* p = str; // p points to a array 
p[1] = 'w';    // valid expression, not str[1] = 'w' is well valid. 
p = "OrangeTorange";   // is valid
// str = "OrangeTorange"; is NOT valid as `str` is not a pointer but array name

Here both operations asked are valid!

Note: Two declarations char *str and char str[] are different. To understand it read: What does sizeof(&arr) return?

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
3

p[1] = 'w' is attempting to modify a string literal, which is illegal. p = "OrangeTorange" is just assigning a different string literal to p, which is fine.

Mud
  • 28,277
  • 11
  • 59
  • 92
0

You can't modify the original string because it's read-only data. You can modify the pointer to point to a different string because the pointer is modifiable. That is, p = "OrangeTorange" is not modifying the original string, only changing where the pointer p points to.

bames53
  • 86,085
  • 15
  • 179
  • 244