strcpy()和字符串左移给出了错误的结果
在某些项目中,我有一段C代码工作错误,但只使用特定的输入字符串。我只编译这篇文章:strcpy()和字符串左移给出了错误的结果,c,linux,string,gcc,strcpy,C,Linux,String,Gcc,Strcpy,在某些项目中,我有一段C代码工作错误,但只使用特定的输入字符串。我只编译这篇文章: #include <stdio.h> #include <stdlib.h> #include <string.h> #define slength 1000 // max string length char ss[slength]; int main(void) { strcpy(ss, "\"abcdefghijkl\""); printf("1 %
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define slength 1000 // max string length
char ss[slength];
int main(void) {
strcpy(ss, "\"abcdefghijkl\"");
printf("1 %s\n",ss);
if (ss[0]=='"') { // remove quotes
printf("2 %s\n",ss);
strcpy(ss, ss+1); // remove first symbol - quote
printf("3 %s\n",ss);
ss[strlen(ss)-1]='\0'; //last symbol
printf("4 %s\n",ss);
}
printf("5 %s\n",ss);
return EXIT_SUCCESS;
}
所以我得到的是'abcdefhhijkl'而不是'abcdefghijkl'。我错在哪里?谢谢
另外,我希望我的代码中没有任何多字节/Unicode字符,但可能需要额外检查
从strcpy(3)
手册:
The strings may not overlap, and the destination string dest must be
large enough to receive the copy. Beware of buffer overruns! (See
BUGS.)
您应该使用memmove(3)
:
。。。而不是
strcpy(ss, ss+1); // remove first symbol - quote
strcpy
中的源字符串和目标字符串不能重叠。您可以尝试memmove(ss,ss+1,strlen(ss)+1)
@MOehmstrlen(ss)+1
:+1
不是必需的。@BLUEPIXY:True。我想包含空终止符,但忘记了第一个字符没有移动,因此-1和+1会相互抵消。抢手货
The strings may not overlap, and the destination string dest must be
large enough to receive the copy. Beware of buffer overruns! (See
BUGS.)
memmove(ss, ss+1, strlen(ss)); // remove first symbol - quote
strcpy(ss, ss+1); // remove first symbol - quote