阅读背景:

你能解释一下这个C程序的输出吗?

来源:互联网 
#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++]) != '
#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?

我想使用while循环将字符串“chicken is good”从ch复制到str。但是当我打印str时,输出显示“chi”。它只打印部分字符串。我的病情错了吗?

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.

我使用Dev c ++作为我的IDE,我的编译器版本是gcc 4.9.2。而且我也是编程新手。

2 个解决方案

#1


2  

strlen(str) has undefined behaviour, because it is reading uninitialized values.

strlen(str)具有未定义的行为,因为它正在读取未初始化的值。

#2


3  

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

语句if(i == strlen(str))中断;由于str尚未终止,因此无用且具有未定义的行为。

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.
  • 必须将main函数的返回值指定为int。您使用的是过时的语法。

  • you do not need separate index variables i and j for the source and destination arrays. They always have the same value.
  • 对于源和目标数组,您不需要单独的索引变量i和j。它们总是具有相同的价值。

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

') { if (i == strlen(str)) break; } printf("%s", str); } #include <stdio.h> #include <string.h> main()



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: