【问题标题】:Can you explain the output in this C program?你能解释一下这个 C 程序的输出吗?
【发布时间】:2017-01-23 23:59:57
【问题描述】:
#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
  • 我知道了@BLUEPIXY

标签: c


【解决方案1】:

语句if (i == strlen(str)) break; 是无用的并且具有未定义的行为,因为str 尚未以空值终止。

请注意,您的程序还有其他问题:

  • 您必须将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;
}

【讨论】:

  • 感谢您的详尽回答并展示了我所有的缺陷@chqrlie
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2016-12-30
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多