该代码循环中为何赋完a就结束循环了?对于s1的输出结果是否以空字符结束?

a1qwertyuiop1 2017-07-23 10:50:48
问题1:该代码循环中为何赋完a就结束循环了,没有完整赋完abc?是不是赋完a后,a后面为空字符不满足循环条件*s1而结束?
问题2:对于s1的输出结果是否以空字符结束?
#include <stdio.h>
#include"stdlib.h"
main()
{
char y[9];
char qw[5];
char *s1="iya";
char *s2="abc";
int i=0;
for(;*s1;s1++,s2++,i++){
y[i]=*s2;
}
s1=&y[0];
printf("%s",s1);
system("pause");
}
...全文
121 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-07-24
  • 打赏
  • 举报
回复
for (A;B;C) D;
//等价于
{
 A;
 while (1) {
  if (!(B)) break;
  D;
  C;
 }
}
a1qwertyuiop1 2017-07-23
  • 打赏
  • 举报
回复
问题修改一下,两者为何有这差别?这段语句的输出结果为“abc” #include <stdio.h> #include"stdlib.h" main() { char y[9]; char qw[5]; char *s1="iya"; char *s2="abc"; int i=0; for(;*s1;s1++,s2++,i++){ y[i]=*s2; } s1=&y[0]; printf("%s",s1); system("pause"); } 收起 这段语句输出结果为"a" #include <stdio.h> #include"stdlib.h" main() { char y[9]; char qw[5]; char *s1="iya"; char *s2="abc"; int i=0; for(;*s1;s1++,s2++,i++){ y[i]=*s2; s1=&y[i]; } s1=&y[0]; printf("%s",s1); system("pause"); }
自信男孩 2017-07-23
  • 打赏
  • 举报
回复
具体循环了几次,可以通过在循环外打印i的值便可以知道。 理论上讲,s1指向字符串结束标记'\0'才会结束循环,那么至少循环3次才可以。循环3次也不能对y后面加上'\0',所以从逻辑上考虑,需要在循环外将字符串'\0'加到y有效字符的后面;
#include <stdio.h>
#include"stdlib.h"
int main()
{
    char y[9];
    char qw[5];
    char *s1="iya";
    char *s2="abc";
    int i=0;
    for(;*s1;s1++,s2++,i++){
        y[i]=*s2;
    }
    printf("i = %d\n", i);
    y[i] = 0;
    s1=&y[0];
    printf("%s\n",s1);
    system("pause");
}
战在春秋 2017-07-23
  • 打赏
  • 举报
回复
引用
为何有这差别
第二种写法是有问题的。 //这个循环并不能如预想的那样结束 for (; *s1; s1++, s2++, i++) { //执行完循环后,会执行s1++,s2++,i++,然后再判断循环条件 y[i] = *s2; s1 = &y[i]; //s1读到'\0'后,在进行下一次判断之前,会先执行s1++,之后*s1又不会等于0,继续循环下去。 } 最终的结果是发生运行时错误。你可以分步调试就能清楚的看到这个过程。

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧