If we show the array, with the corresponding pointers added, it will look something like this:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
| 'S' | 'h' | 'o' | 'r' | 't' | ' ' | 'M' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
^ ^ ^
| | |
s1 s2 s3
When you modify the contents of the array, the pointers s2
and s3
themselves doesn't change, they still point to the same locations in the array.
So after
strncpy(s1 + 1, s2, 1);
the array (with pointers) looks like
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
| 'S' | 'M' | 'o' | 'r' | 't' | ' ' | 'M' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
^ ^ ^
| | |
s1 s2 s3
The single character that s2
is pointing to is copied to s1[1]
.
Then with
strcpy(s1 + 2, s3);
the array looks like
+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
| 'S' | 'M' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+
^ ^ ^
| | |
s1 s2 s3
The sub-string "Service"
is copied over part of the string beginning on s1[2]
.
The pointer s2
is still pointing to the same location, but if we consider s2
as a pointer to the first character of a string then its contents have changed because you have overwritten that contents.