[英]Can you explain the output in this C program?
#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);
}
我想使用while
循環將字符串"chicken is good"
從ch
復制到str
。 但是當我打印str
,輸出顯示為"chi"
。 它只打印部分字符串。 我的狀況不對嗎?
我使用Dev c ++作為我的IDE,我的編譯器版本是gcc 4.9.2。 而且我還是編程新手。
語句if (i == strlen(str)) break;
是沒有用的,並且具有不確定的行為,因為str
尚未為null終止。
請注意,您的程序還有其他問題:
main
函數的返回值指定為int
。 您正在使用過時的語法。 i
和j
。 它們始終具有相同的價值。 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;
}
strlen(str)
具有未定義的行為,因為它正在讀取未初始化的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.