我有一个关于使用strcpy的问题.我知道ANSI C标准说:源和目标不能重叠,否则行为是不可预测的.我向您展示了一段代码,如果它是在Linux下使用旧的gnu C编译器编译的话,它可以正常工作.
#include <string.h>
#include <stdio.h>
char S[80],*P;
int main() {
strcpy(S,"abcdefghi\r\njklmnopqr\r\nstuvwxyz\r\n");
for (P=S; P=strchr(P,'\r'); P++) strcpy(P,P+1);
printf("%s\n",S);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此序列\r
从输入字符串中删除每个(回车).我知道(来自Kernigham和Ritchie)strcpy的一个非常简单的实现如下
while (*t++=*s++) ;
Run Code Online (Sandbox Code Playgroud)
现在我使用gcc(Gentoo 4.5.4 p1.0,pie-0.4.7)4.5.4编译我的程序,它打印出来:
abcdefghi
jklmnpqr <-- missing 'o'
stuvwxxyz <-- doubled 'x'
Run Code Online (Sandbox Code Playgroud)
我想这个编译器(实际上它的库)使用了非常复杂的序列strcpy
,我不明白其中的原因.