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";
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";
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?
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.
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.