《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
关键的错误是
在s指向\0时候停止增加指针。
而
在指向\0时候仍为指针增加了1。从而使得两段拼接的字符串中间存在\0,printf在这个中间点认为字符串已经结束。