In practicing for final exam in my high school, we got following question:
Find values of strings s1, s2 and s3 after code executed:
char s1[] = "Short Message Service", *s2, *s3;
s2 = strchr(s1, 'M');
s3 = strrchr(s2,'S');
strncpy(s1 + 1, s2, 1);
strcpy(s1 + 2, s3);
Whole class expected result to be:
s1 = SMService
s2 = Message Service
s3 = Service
When we tested it by executing code we were surprised to see result is:
s1 = SMService
s2 = ice
s3 = Service
The problem is nobody can figure out why s2 got shortened. While trying to figure it out, I found out s2 is remaining "Message Service" until the last line of code where "strcpy" function executes. I assume the problem might be in pointer addresses but I couldn't figure out how strcpy is affecting s2.
So my question is why s2 isn't what we expected it to be and why it got shortened?