簡體   English   中英

您可以在這個C程序中解釋輸出嗎?

[英]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 您正在使用過時的語法。
  • 您不需要為源數組和目標數組使用單獨的索引變量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;
}

strlen(str)具有未定義的行為,因為它正在讀取未初始化的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM