简体   繁体   中英

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);
}

I want to copy the string "chicken is good" from ch to str using a while loop. But when I print str the output shows "chi" . It only prints part of the string. Is my condition wrong?

I am using Dev c++ as my IDE and the version of my compiler is gcc 4.9.2. And also I am new to programming.

The statement if (i == strlen(str)) break; is useless and has undefined behavior since str is not yet null terminated.

Note that your program has other problems:

  • you must specify the return value of the main function as int . You are using an obsolete syntax.
  • you do not need separate index variables i and j for the source and destination arrays. They always have the same value.
  • you should print a newline at the end of your message.
  • for good style, you should return 0 at the end of main() .

Here is a simpler version:

#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)具有未定义的行为,因为它正在读取未初始化的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM