1
char* a = "string"; /*"string" is a string literal, thus modifying
value isn't allowed, but then why */
char b[] = "string1"; /*"string1" is
also a string literal but why modification of this is allowed? */

a[1] = 's'; //this is not allowed b[1] = 'p'; //this is allowed

Why can char array be modified when it is clearly pointing to a string literal?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Renz Carillo
  • 349
  • 2
  • 11
  • 4
    I believe when you do `char* a = "string"` you get a pointer to the read only memory, but when you do `b[] = "string1"` you get a copy of the string on the stack – pqnet Apr 13 '21 at 08:12
  • 1
    Does this answer your question? [What is the difference between char s\[\] and char \*s?](https://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s) – mediocrevegetable1 Apr 13 '21 at 08:14
  • 1
    The array does not point to anything - arrays are not pointers. It is a copy of the initializer and this works the same as if you wrote `char b[] = {'s','t','r','i','n','g','1','\0'};`. – molbdnilo Apr 13 '21 at 08:14
  • The string `"string1"` is a literal, you're right. But `b[]` is not a literal. It is a variable, an array whose size and items' initial values are taken from that literal. So `"string1"` is read-only and `b[]` is not. – CiaPan Apr 13 '21 at 08:36

1 Answers1

5

when it is clearly pointing to a string literal?

No. Given char b[] = "string1";, b is not a pointer pointing to the string literal, but a char array containing copy of "string1". The modification on the string literal leads to UB, but modification on the char array is fine.

String literals can be used to initialize character arrays. If an array is initialized like char str[] = "foo";, str will contain a copy of the string "foo".

BTW char* a = "string"; is not allowed since C++11; you have to write it as const char* a = "string";.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405