-4

I know when we declared a char *c ="Hello"; means that we cannot modify this string. But how come I was able to modify this array of string in C.

char *p [] = {"Hello","World"}; 
*p = "Mode";

Should not that give me an error for attempting to modify it?

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • Take a look at this answer it is quite good to understand the concept of strings. http://stackoverflow.com/a/1011545/2555668 – usamazf Mar 24 '16 at 09:47
  • 1
    @irqed This is not a duplicate of that question. – Jonathon Reinhart Mar 24 '16 at 09:55
  • Related: http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Lundin Mar 24 '16 at 10:09
  • @Lundin this is irrelevant to my question. – Abdulaziz Asiri Mar 24 '16 at 10:12
  • @AbdulazizAsiri No it isn't. If you understood the differences between an array, a pointer, and an array of pointers, you wouldn't be asking this question. – Lundin Mar 24 '16 at 10:14
  • @Lundin I agree that if the OP understood arrays of pointers we wouldn't be here, but it is different. That question never mentions an array of pointers. It only compares `char *s = "abc"` to `char s[] = "abc"`. – Jonathon Reinhart Mar 24 '16 at 10:35
  • @JonathonReinhart If you understand that `char* p` is a pointer and `char arr[]` is an array, then you should be able to tell `char*p []` is an array of pointers. Which is something completely unrelated to modifying string literals... – Lundin Mar 24 '16 at 10:44

2 Answers2

6

You're not modifying a string (literal) anywhere.

 char *p [] = {"Hello","World"};

Here p is an array (size 2) of pointer-to-char. It's a variable, there's nothing read-only about it. The strings it currently points to however are read-only.

*p = "Mode";

You're simply changing the first element of that array to point to a different (read-only) string. This is the same as:

p[0] = "Mode";
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

p is an array of pointers.These pointers are modifiable,however their targets(the things they point to) are not.

*p is equivalent to p[0] which is the first pointer in the array.

*p = "Mode" modify the value of the pointer p[0],not the string literal "hello".

machine_1
  • 4,266
  • 2
  • 21
  • 42