我有一个关于使用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;
}
这个序列从输入字符串中删除每一个\r
(回车符)。从Kernigham和Ritchie的书中了解到,一个非常简单的strcpy实现如下:
while (*t++=*s++) ;
现在我使用gcc (Gentoo 4.5.4 p1.0, pie-0.4.7) 4.5.4编译我的程序,它输出如下:
abcdefghi
jklmnpqr <-- missing 'o'
stuvwxxyz <-- doubled 'x'
我猜想这个编译器(实际上是它的库)对于strcpy
使用了非常复杂的序列,但我不明白原因。
long long *
),并进行复制。这意味着复制会覆盖正在被复制的内容。 - Some programmer dude