代码:
#include <stdio.h>
int main()
{
char str1[]="bombay";
char str2[]="pune";
char *s1 = str1;
char *s2 = str2;
while(*s1++ = *s2++);
printf("%s\n",str1);
}
输出:(GCC 编译器)
pune
但根据我的说法,输出应该是puneay
。应该复制 pune
来代替 bomb
,其余的应该保持原样。
那么,为什么编译器会给出此代码的输出 "pune" 而不是 "puneay"?
最佳答案
同样被复制的字符串末尾有一个空终止符。
当复制空终止符时,while 停止执行,并打印结果。
因此 str1
的内存实际上包含:'p' 'u' 'n' 'e' '\0' 'y' '\0'
关于关于 C 中 "while(*s1++ = *s2++);"的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51840835/