繁体   English   中英

C strcpy和strncpy组合的意外结果

[英]unexpected result in C strcpy and strncpy combination

在我高中的期末考试练习中,我们遇到以下问题:

执行代码后查找字符串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);

全班预期结果为:

s1 = SMService
s2 = Message Service
s3 = Service

当我们通过执行代码对其进行测试时,我们惊讶地看到结果是:

s1 = SMService
s2 = ice
s3 = Service

问题是没有人能弄清楚为什么s2被缩短了。 在尝试弄清楚时,我发现s2仍然是“消息服务”,直到执行“ strcpy”功能的最后一行代码为止。 我认为问题可能出在指针地址中,但我无法弄清楚strcpy如何影响s2。

所以我的问题是,为什么s2不是我们期望的那样,为什么它缩短了?

在您的代码中, 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