关于"while(*s1 ++ =*s2 ++);"的困惑 在C.

msc*_*msc 1 c pointers

码:

#include <stdio.h>

int main()
{
    char str1[]="bombay";
    char str2[]="pune";

    char *s1 = str1;
    char *s2 = str2;

    while(*s1++ = *s2++);
    printf("%s\n",str1);
}
Run Code Online (Sandbox Code Playgroud)

输出:( GCC编译器)

pune
Run Code Online (Sandbox Code Playgroud)

但根据我的输出应该是puneay.pune应该复制代替,bomb休息应该是原样.

那么,为什么编译器会输出这段代码"pune"而不是"puneay"

小智 12

在字符串的末尾有一个空终止符,它也被复制.

复制null终止符时,停止执行,并打印结果.

所以内存str1实际上包含:'p' 'u' 'n' 'e' '\0' 'y' '\0'