c - 字符串复制函数: simple issue

标签 c pointers dereference post-increment

我有一个函数可以获取两个指向字符串的指针。

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/

相关文章:

c - 在多进程 scanf 的 MPI 中只接受一次输入并将垃圾值分配给其他?

c - 编译调用外部库的 cython 代码时出现链接错误

c - 链表插入函数 - 通过指针传递列表

c++ - 如何取消引用数组元素 (C++)

qt - 将 QFile 传递给函数

c - 如何从 stdio 打印和读取字符串

c - 我的程序收到错误 'stray '\16 0' in program '

c++ - 如何从另一个类中的私有(private)指针指向的类中获取私有(private)信息?

c - sscanf : Get a pointer to end position

c - 取消引用指针错误