2017-01-23 91 views
0
#include <stdio.h> 
#include <string.h> 

main() { 
    int i = 0, j = 0; 
    char ch[] = { "chicken is good" }; 
    char str[100]; 
    while ((str[i++] = ch[j++]) != '\0') { 
     if (i == strlen(str)) 
      break; 
    } 
    printf("%s", str); 
} 

我想串"chicken is good"ch使用while循环复制到str。但是,当我打印str输出显示"chi"。它只打印部分字符串。我的病情是错的吗?你能解释这个C程序中的输出吗?

我使用Dev C++作为我的IDE,我的编译器的版本是gcc 4.9.2。而且我也是编程新手。

+4

删除'如果(我== strlen的(STR)) break' – BLUEPIXY

+0

我得到了它@BLUEPIXY – kryptokinght

回答

2

strlen(str)有未定义的行为,因为它正在读取未初始化的值。

+0

我得到了它,感谢您的答复 – kryptokinght

3

陈述if (i == strlen(str)) break;是无用的,并且由于str尚未空终止而具有未定义的行为。

请注意,你的程序有其他问题:

  • 您必须指定main函数的返回值int。您正在使用过时的语法。
  • 对于源和目标阵列,您不需要单独的索引变量ij。它们始终具有相同的价值。
  • 您应该在邮件末尾打印换行符。
  • 为了好风格,您应该在main()的末尾返回0

下面是一个简单的版本:

#include <stdio.h> 

int main(void) { 
    int i; 
    char ch[] = "chicken is good"; 
    char str[100]; 

    for (i = 0; (str[i] = ch[i]) != '\0'; i++) { 
     continue; 
    } 
    printf("%s\n", str); 
    return 0; 
} 
+0

谢谢精心制作答案并展示我的所有缺陷@chqrlie – kryptokinght