简体   繁体   English

C strcpy和strncpy组合的意外结果

[英]unexpected result in C strcpy and strncpy combination

In practicing for final exam in my high school, we got following question: 在我高中的期末考试练习中,我们遇到以下问题:

Find values of strings s1, s2 and s3 after code executed: 执行代码后查找字符串s1,s2和s3的值:

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. 问题是没有人能弄清楚为什么s2被缩短了。 While trying to figure it out, I found out s2 is remaining "Message Service" until the last line of code where "strcpy" function executes. 在尝试弄清楚时,我发现s2仍然是“消息服务”,直到执行“ strcpy”功能的最后一行代码为止。 I assume the problem might be in pointer addresses but I couldn't figure out how strcpy is affecting s2. 我认为问题可能出在指针地址中,但我无法弄清楚strcpy如何影响s2。

So my question is why s2 isn't what we expected it to be and why it got shortened? 所以我的问题是,为什么s2不是我们期望的那样,为什么它缩短了?

In your code s2 was pointing to the M in s1 and then got overwritten by s3 in your last strcpy : 在您的代码中, s2指向s1M ,然后在最后一个strcpys3覆盖:

char s1[] = "Short Message Service", *s2, *s3;
s2 = strchr(s1, 'M');   // s2 is pointing to s1 + 6 = Message Service
s3 = strrchr(s2, 'S');  // s3 is pointing to s1 + 14 = Service 
strncpy(s1 + 1, s2, 1); // Write M in to s1[1], s1 = SMort Message Service 
strcpy(s1 + 2, s3);     // Write Service into s1 + 2
                        // s1 = SMService but s2 is pointing to s1 + 6 = ice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM