2017-01-23 81 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