[英]String concatenation using pointers in C
I am concatenating a string (t) at the end of another string (s) in this code but stuck in the use of operators and their precedence in the loop ( while() )我在此代码中将一个字符串 (t) 连接到另一个字符串 (s) 的末尾,但一直使用运算符及其在循环中的优先级 ( while() )
1.
while(*s++);
1.while
while(*s++);
doesn't do the work不做工作
2.
while(*s) ++s;
2.while
while(*s) ++s;
does做
But what is the difference between them ?但是它们之间有什么区别呢?
#include<stdio.h>
void strcat(char *, const char *);
int main(void){
char s[100] = "Aditya ";
char t[100] = "Kumar";
strcat(s, t);
printf("%s ", s);
return 0;
}
void strcat(char * s, const char * t){
while(*s)
s++;
while(*s++ = *t++);
}
Why in the strcat() function in first while while(*s++);
为什么在 strcat() 函数中首先 while
while(*s++);
doesn't concatenate the string but while(*s) s++;
不连接字符串,而是连接
while(*s) s++;
does I guess they work the same way ?我猜他们的工作方式是一样的吗?
they aren't equivalent.它们不是等价的。
while(*s++);
increments the pointer no matter what, so when *s
is \\0
, the pointer is incremented once more.无论如何都会增加指针,所以当
*s
是\\0
,指针会再次增加。 And the concatenation happens after the nul-terminator.连接发生在空终止符之后。 The rest of the buffer contains zeroes so it doesn't crash but it doesn't do the job.
缓冲区的其余部分包含零,因此它不会崩溃,但不会完成工作。
while(*s) { s++; }
stops when *s
is \\0
.当
*s
为\\0
时停止。 So no extra incrementation is performed.所以没有执行额外的增量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.