C 条件是什么:'*s1=*s2';你到底是怎么做的?

C 条件是什么:'*s1=*s2';你到底是怎么做的?,c,pointers,for-loop,C,Pointers,For Loop,考虑以下代码: void concatenate(char *s1, char *s2){ while(*s1 != '\0'){ s1++; } for (; *s1 = *s2; s1++, s2++){ } } 在上述函数中,每次检查for循环中的条件*s1=*s2。这怎么可能呢? 它还将s2所指的值分配给s1所指的值,然后为循环继续检查什么?分配的值就是检查的值。分配该值,然后如果该值为零(表示字符串结束),则循环退出 在C语言中

考虑以下代码:

void concatenate(char *s1, char *s2){
    while(*s1 != '\0'){
       s1++;
    }
    for (; *s1 = *s2; s1++, s2++){  
    }   
}
在上述函数中,每次检查for循环中的条件
*s1=*s2
。这怎么可能呢?

它还将
s2
所指的值分配给
s1
所指的值,然后为循环继续检查什么?

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


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

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

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


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

这是连接两个字符串的程序。使用第一个while循环指针返回到字符串“s1”的末尾。现在在for循环中,
s2
中的每个字符都被分配到
s1

我已经重新格式化了代码,这样看起来更好,更容易解释,我已经以注释的形式添加了解释

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

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


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

for循环运行,直到其条件表达式为true(表示不为零)。当到达字符串s2的结尾时,即“\0”,它与0(false)相同,它被分配给*s1,并且为零,因此现在条件表达式为false,因此退出for循环

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) 
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++)
        ;
}