我有一个函数可以获取两个指向字符串的指针。
void copy(char *s, char *t){ /*copy the string pointed by t into string pointed by s*/
while( (*s = *t) != '\0'){
s++;
t++;
}
return;
}
问题是:我发现它可以与 s++
和 t++
(这意味着“指针,转到下一个字符并检查它”)和 一起使用>*s++
和 *t++
。所以我问这不应该 *s++
修改指针指向的字符吗?为什么效果一样?
在 ubuntu 中编译并带有一些示例字符串。 提前致谢
最佳答案
有两个部分。
首先:
both with s++ and t++ (that means "pointers, go to next character and check it") and with *s++ and *t++.
嗯,你看到的结果是相同的,但这并不意味着它们是相同的。
如果是这样的片段
s++;
t++;
和
*s++;
*t++;
它们产生相同的行为,就像在这两种情况下一样,只有后增量的副作用(因为它们是持久的,影响实际变量),而不是产生的结果(结果应用解引用运算符的过程被丢弃)。
实际上,如果您尝试编译第二个版本(*s++;
thingy),您会收到类似的警告
Warning: value computed is not used [-Wunused-value]
然后,第二:
shouldn't
*s++
be modifying the character pointed by the pointer
不,请阅读 operator precedence 。后增量绑定(bind)高于解引用运算符,副作用在结果的值计算之后开始,即解引用操作。
关于c - 字符串复制函数: simple issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801217/