gpt4 book ai didi

c - strcpy如何改变string的值

转载 作者:行者123 更新时间:2023-12-02 06:26:20 24 4
gpt4 key购买 nike

我得到了这个家庭作业来决定下面的代码将做什么(在纸上,没有在计算机上测试)。

char s1[]="Short Message Service", *s2, *s3;
s2=strchr(s1,'M');
s3=strchr(s2,'S');
strncpy(s1+1,s2,1);
strcpy(s1+2,s3);

当我想检查我做的是否正确时,我在电脑上运行它并得到了这个结果:

s1 = SMservice 

s2 = ice

s3 = Service

我以为 s2 将是 “消息服务” 但它变成了 “ice”。显然它在 strcpy(s1+2,s3) 被调用后改变了;有人可以解释该函数为什么以及如何影响 s2 吗?

最佳答案

答案是“未定义的行为”——任何事情都有可能发生。 strcpy()strncpy() 的参数不得重叠。 — 但在这里,strcpy() 的参数确实重叠。

C11 §7.24.2.3 The strcpy function ¶2 :

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

§7.24.2.4 The strncpy function ¶2

The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.308) If copying takes place between objects that overlap, the behavior is undefined.

308) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.

这意味着无法给出可靠的答案。您可能会决定然后描述如果复制操作从源头开始复制到目标会发生什么,这可能是您的教师所期望的。但这不是保证的行为。

给定以下代码和从左到右的复制假设:

char s1[] = "Short Message Service";
char *s2 = strchr(s1, 'M');
char *s3 = strrchr(s2, 'S');
strncpy(s1+1, s2, 1);
strcpy(s1+2, s3);

我们可以推导出s2指向&s1[6]s3指向&s1[14] (这是强制性的)。 s1中各个阶段的值是:

s1 = "Short Message Service"   -- initial text
s1 = "SMort Message Service" -- after strncpy
s1 = "SMService" -- after strcpy (but this assumes UB works as expected)

因此,如您所见,从 s2 开始的字符串现在包含 ice

但是,必须再次强调,这不是必需的行为。

关于c - strcpy如何改变string的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61800177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com