我在此代码中将一个字符串 (t) 连接到另一个字符串的末尾,但在循环中使用运算符及其优先级 ( while() )
1.
while(*s++);
doesn't do the work2.
while(*s) ++s;
does
但是它们之间有什么区别呢?
#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++);
}
为什么在第一个 while while(*s++);
的 strcat() 函数中没有连接字符串,但我猜 while(*s) s++;
会连接字符串他们的工作方式相同吗?
最佳答案
它们并不等同。
while(*s++);
无论如何都会递增指针,因此当*s
为\0
时,指针会再次递增。连接发生在空终止符之后。缓冲区的其余部分包含零,因此它不会崩溃,但它不会完成这项工作。
while(*s) { s++; }
当*s
为\0
时停止。因此不会执行额外的增量。
关于c - C 中使用指针的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46696163/