【问题标题】:What does the condition: '*s1 = *s2' do exactly?条件:'*s1 = *s2' 到底是做什么的?
【发布时间】:2013-08-02 02:00:18
【问题描述】:

考虑以下代码:

void concatenate(char *s1, char *s2){
    while(*s1 != '\0'){
       s1++;
    }
    for (; *s1 = *s2; s1++, s2++){  
    }   
}

在上面的函数中,在for循环中,条件*s1 = *s2每次都会被检查。这怎么可能?
它还将s2 指向的值分配给s1 指向的值,然后检查什么以使循环继续?

【问题讨论】:

    标签: c pointers for-loop


    【解决方案1】:

    指令"*s1 = *s2s2地址处的值复制到s1地址处的值,然后该值成为for循环中的中断条件,因此循环运行直到找到等于0\0。 (注意,\0 nul char 的 ASCII 值为零 = false 在 C 中)。

    for (; *s1 = *s2  ; s1++, s2++)
               ^           ^ 
               |           | 
            assign         increments both 
            *s2 to *s1,     
           then break condition = *s1  (updated value at *s1 that is \0 at the end) 
    

    这是您将字符串从s2 复制到s1 的方法,并检查字符串终止符号是否来自\0(=0 作为 ASCII 值)。

    【讨论】:

      【解决方案2】:

      我已经重新格式化了代码,使它看起来更好并且更容易解释,我以 cmets 的形式添加了解释。

      我还按照编译器的建议在赋值周围添加了括号(在启用警告的情况下编译时)。

      void concatenate(char *s1, char *s2)
      {
          /* s1 initially points to the first char of the s1 array,
           * this increments it until it's reached the end */
          while(*s1 != '\0')
              s1++;
      
      
          /* the initialisation part is empty as there's no initial assignment
           * the test condition tests if assignment evaluates to positive, 
           * when null terminator is reached it will evaluate to negative 
           * which will signal the end of the loop
           * the afterthought increments both pointers
           * */
          for (; (*s1 = *s2)  ; s1++, s2++)
              ;
      }
      

      请注意,此函数非常不安全,因为在没有空终止符的情况下,指针可能会递增以指向无效内存。

      它也不检查s1 是否足够大以容纳s2

      【讨论】:

        【解决方案3】:

        被分配的值是被检查的。该值被赋值,然后如果该值为零(表示字符串结束),则循环退出。

        在 C 中,赋值操作也是一个表达式,表达式的值就是被赋值的值。

        【讨论】:

          【解决方案4】:

          s1s2 都是指针。 *s1 是指针指向的位置的。由于您在 for 循环中移动了两个指针,因此您每次遇到该条件时都会比较不同的 values

          【讨论】:

            【解决方案5】:

            这是连接两个字符串的程序。第一个 while 循环指针到达字符串 's1' 的末尾。现在在 for 循环中,s2 中的每个字符都分配给 s1

            【讨论】:

              【解决方案6】:

              for 循环一直运行直到它的条件表达式为真(表示不为零)。当到达字符串 s2 的末尾,即 '\0' 与 0(false) 相同时,它被赋值给 *s1 并且它为零,所以现在条件表达式为 false 退出 for 循环

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-05-12
                • 1970-01-01
                • 1970-01-01
                • 2015-08-06
                • 2013-09-02
                • 2014-01-02
                相关资源
                最近更新 更多