为什么下面的代码的输出是“pune”?了解使用C语言中的指针交换两个字符串
#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();
}
为什么下面的代码的输出是“pune”?了解使用C语言中的指针交换两个字符串
#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();
}
你已经写了while(* s1 ++ = * s2 ++); 末尾的分号意味着while被视为语句而不是循环。 所以你试图将s2的每个字符拷贝到s1。所以,在将'pune'复制到s1之后,在s1的末尾会出现一个空字符。现在null也被复制到s2中。在打印字符串s1时,%s将打印该字符串,直到找到空。因此你得到了pune作为输出。
他们没有被交换。 – 2014-09-27 10:56:20
但是你期望输出是什么? – 2014-09-27 10:57:19
此代码'while(* s1 ++ = * s2 ++);'一开始就无法读取 – 2014-09-27 10:58:49