Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
StringCopy函数:简单问题_C_Pointers_Dereference_Post Increment - Fatal编程技术网

StringCopy函数:简单问题

StringCopy函数:简单问题,c,pointers,dereference,post-increment,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++中都能工作。所以我想问的是

我有一个函数,它有两个指向字符串的指针

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中编译。 提前感谢

共有两部分

首先

使用s++和t++(即“指针,转到下一个字符并检查它”)以及使用*s++和*t++

你看到的结果是一样的,但这并不意味着它们是一样的

如果是这样的代码片段

    s++;
    t++;

它们产生相同的行为,因为在这两种情况下,只有增量后事项的副作用(因为它们是持久的,影响实际变量),而不是产生的结果(应用解引用运算符的结果被丢弃)

实际上,如果您尝试编译第二个版本(
*s++;
thingy),您将得到如下警告

警告:未使用计算值[-Wunused value]

然后,第二个

*s++
不应该修改指针指向的字符吗


不,读一下。后增量绑定高于取消引用操作符的绑定,副作用在结果的值计算后生效,即取消引用操作。

对于初学者,最好使用限定符
const
声明第二个参数

void copy(char *s, const char *t);
函数和函数用户之间的约定是函数保证复制的源字符串不会更改

如果将函数声明为

char * copy(char *s, const char *t);
void copy(char *s, char *t){    /*copy the string pointed by t into string pointed by s*/

    while( (*s = *t) != '\0'){
        *s++;
        *t++;
    }
    // return;
}
当函数返回指向结果字符串的第一个字符的指针时

对于原来的问题,如果你把函数写成

char * copy(char *s, const char *t);
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++
的值。因此在这种情况下,指针的解引用是冗余操作

但是,在解引用有意义的情况下,可以按照以下方式编写函数

void copy(char *s, char *t){    /*copy the string pointed by t into string pointed by s*/

    while( ( *s++ = *t++) != '\0');
    // return;
}

猜猜什么也行<代码>while(*s++=*t++)顺便说一句,您的参数命名很奇怪,因为我脑海中从
s
t
出现的第一个单词对是源和目标。“难道
*s++
不应该修改指针指向的字符吗?”--修改指向的字符的语句是
(*s)++
。我还可以删除
!='\0'
,我说得对吗?@MarkiplierB是的,你在写。你可以边写边写(*s++=*t++);