《C程序设计语言》第二版的习题5.1:用指针的方式实现strcat即字符串连接函数。
这个是可以实现的
#include <stdio.h>
void strcatp(char *s, char *t);
int main()
{
char s[] = "Hello";
char t[] = " world!";
strcatp(s, t);
printf(s);
return 0;
}
void strcatp(char *s, char *t){
while(*s)
s++;
while(*s++ = *t++)
;
}
输出结果为Hello world!
而这种却不行?
#include <stdio.h>
void strcatp(char *s, char *t);
int main()
{
char s[] = "Hello";
char t[] = " world!";
strcatp(s, t);
printf(s);
return 0;
}
void strcatp(char *s, char *t){
while(*s++)
;
while(*s++ = *t++)
;
}
输出结果:Hello
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
关键的错误是
while(*s)
s++;
在s指向\0时候停止增加指针。
而
while(*s++)
在指向0时候仍为指针增加了1。从而使得两段拼接的字符串中间存在0,printf在这个中间点认为字符串已经结束。