简体   繁体   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);
}

I want to copy the string "chicken is good" from ch to str using a while loop. 我想使用while循环将字符串"chicken is good"ch复制到str But when I print str the output shows "chi" . 但是当我打印str ,输出显示为"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. 我使用Dev c ++作为我的IDE,我的编译器版本是gcc 4.9.2。 And also I am new to programming. 而且我还是编程新手。

The statement if (i == strlen(str)) break; 语句if (i == strlen(str)) break; is useless and has undefined behavior since str is not yet null terminated. 是没有用的,并且具有不确定的行为,因为str尚未为null终止。

Note that your program has other problems: 请注意,您的程序还有其他问题:

  • you must specify the return value of the main function as int . 您必须将main函数的返回值指定为int You are using an obsolete syntax. 您正在使用过时的语法。
  • you do not need separate index variables i and j for the source and destination arrays. 您不需要为源数组和目标数组使用单独的索引变量ij 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() . 为了保持良好的风格,您应该在main()的末尾返回0

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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