了解在C语言中使用指针交换两个字符串

了解在C语言中使用指针交换两个字符串,c,pointers,while-loop,C,Pointers,While Loop,为什么下面代码的输出是“pune” #包括 #包括 int main() { char str1[]=“孟买”; 字符str2[]=“pune”; char*s1=str1,*s2=str2; 而(*s1++=*s2++); printf(“%s”,str1); printf(“\n”); getch(); }您只是将s2复制到s1。因此很明显,输出应该是您在编写while(*s1++=*s2++)时编写的“pune”; 结尾的分号表示while作为语句而不是循环。 因此,您正在尝试将s2的每

为什么下面代码的输出是“pune”

#包括
#包括
int main()
{
char str1[]=“孟买”;
字符str2[]=“pune”;
char*s1=str1,*s2=str2;
而(*s1++=*s2++);
printf(“%s”,str1);
printf(“\n”);
getch();

}您只是将s2复制到s1。因此很明显,输出应该是您在编写while(*s1++=*s2++)时编写的“pune”

; 结尾的分号表示while作为语句而不是循环。
因此,您正在尝试将s2的每个字符复制到s1。因此,将“pune”复制到s1后,s1的末尾存在一个空字符。现在null也被复制到s2中。打印字符串s1时,%s将打印字符串,直到找到null。因此您将pune作为输出。

它们没有被交换。但是您希望输出是什么?此代码
while(*s1++=*s2++)对于一个星来说是不可读的。幸运的是pune比Bombay小。有人能在这里解释while循环的工作吗?它的终止条件是(*s1==0),虽然没有出现这种情况,但您正在将每个字符从s2复制到s1,并递增两个指针。
#include <stdio.h>
#include<conio.h>
int main()
 {
char str1[]="bombay";
char str2[]="pune";
char *s1=str1,*s2=str2;
while(*s1++=*s2++);
printf("%s",str1);
printf("\n");
getch();