问题描述
我在这里阅读有关K&R书中的指针
https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf
/* strcpy: copy t to s; pointer version */
void strcpy(char *s,char *t) {
while ((*s = *t) != ’\0’) {
s++;
t++;
}
}
但是我不明白while ((*s = *t) != ’\0’)
中有2个()行。
我了解到的是将其用作:while( condition )
!
解决方法
98
87
79
78
69
98
98
实际上,有一个分配,然后是一个比较:
-
while ((*s = *t) != ’\0’)
- 如果等于循环结束,则将此字符的值与
*s = *t; // copy the character *t in the string s
比较
为了减少代码行数,将它们全部放在一行中。
,这是一种非常密集的书写方式:
void strcpy(char *s,char *t) {
while (true) {
// The condition in the loop in your question
*s = *t;
if (*s == '\0)
break;
// The body in the loop in your question
s++;
t++;
}
}
K&R书中较短的(在代码行中)版本有效,因为表达式(*s = *t
)有两件事:
- 它将
*s
中的值分配给*t
。 - 表达式
(*s = *t)
的值为*t
。
因此,如果将*t
分配给*s
到*t == '\0'
,我们可以用它打破循环。