【发布时间】:2015-02-12 03:16:55
【问题描述】:
最近我一直在学习 C 和指针。
在 Stephen G. Kochan 的《Programming in C》一书中,我遇到了一个我很难完全理解的例子。
使用指针将字符串from复制到字符串to,示例说明:
void copyString (char *to, char *from) {
while ( *from )
*to++ = *from++;
*to = '\0';
}
在我的理解中,*from++ 是*from 的后增量;因此*to++ 的值应仅为*from。
例如,如果
`*from` is in the position 1.
`*from++` is in position 2
`*to++` in position 2,
但是:*from++ = *to++ 应该将 *from 的值返回为 *to 位置 1,而不是 2。
编译器说是位置2,书上也说是位置2。
我在这里有点困惑。你对这个案例有什么可行的解释吗?
【问题讨论】:
-
相当于:
*to = *from; to++; from++;- 太可怕了,不是吗? -
K&R 方法更短:
while (*to++ = *from++) {;}
标签: c pointers post-increment