使用带有后增量的指针复制字符

cuo*_*gtn 1 c pointers post-increment

最近我一直在学习C和指针.

在Stephen G. Kochan撰写的"C编程"一书中,我遇到了一个例子,我很难完全理解它.

要使用指针将字符串复制from到字符串to,示例表明:


void copyString (char *to, char *from) {
    while ( *from ) 
         *to++ = *from++;

    *to = '\0'; 
}
Run Code Online (Sandbox Code Playgroud)

在我的理解中,*from++是一个后增量*from; 因此,价值*to++应该*from只是.

例如,如果

`*from` is in the position 1.

`*from++` is in position 2

`*to++` in position 2, 
Run Code Online (Sandbox Code Playgroud)

但是:*from++ = *to++应返回的值*from作为*to位置1,而不是2.

编译器说这是第2位,该书还说它的位置是2.

我在这里有点困惑.你对这个案子有什么可行的解释吗?

250*_*501 5

使用后缀++一元运算符时,在计算操作数的值后对增量进行排序.所以表达式相当于:

*to = *from;
to++ ;
from++ ;
Run Code Online (Sandbox Code Playgroud)

在您的示例:*to++ = *from++;,的值*to*from获得,然后的值 *from被分配给*to,然后两个指针递增.