0

Here is an example

char *pointer = “abc”;

if i try to change this string *(pointer+1)='D';

it returns 255 error, why?

daboor
  • 33
  • 3
  • Does this answer your question? [Why should I use a pointer rather than the object itself?](https://stackoverflow.com/questions/22146094/why-should-i-use-a-pointer-rather-than-the-object-itself) – fuggerjaki61 Jul 22 '20 at 15:24

1 Answers1

0

The short answer is because that's in the definition of the language

The longer answer is that strings that are included in the program are part of the compiled program file, like the code itself. That is generally read-only in most modern operating systems. To make those strings writeable, the operating system or the language runtime would have to copy them into a writeable data block. Since that costs time and memory, and isn't usually what people want, C++ doesn't do it by default.

Andrew McGuinness
  • 2,092
  • 13
  • 18
  • But if the string is declared as an array[]="String"; then it can be changed. Assigning it to a pointer and making it changeable is dangerous at some level? – daboor Jul 22 '20 at 15:00
  • It's not fundamentally about danger, it's about whether you're copying the data into your program's data area or not. array[]="String" is a copy instruction -- create an array (in your program's data) and initialize it by copying those seven characters from the code area – Andrew McGuinness Jul 22 '20 at 15:06