【问题标题】:C-Array output is different than expected for same printf() [duplicate]C-Array输出与相同printf()的预期不同[重复]
【发布时间】:2014-07-31 09:02:28
【问题描述】:

我正在尝试执行“查找错误”任务,而这一小段 C 代码(不能按原样运行)应该有错误。可惜我一个也找不到。我将它放入可运行的代码中,它似乎按预期运行......这是一个技巧问题还是我错过了什么?非常感谢任何帮助。

代码片段:

void example(int a[10]){
        int i = 0;
        do {
           a[i] = i++;
        }while (i < 10);
    }

我的可运行代码:

#include <stdio.h>
#include <string.h>

example(int a[10]){
    int i = 0;
    do {
       a[i] = i++;
       printf("%i", a[i-1]);  //decremented by 1 to offset i
    }while (i < 10);
}

int main(void)
{
   int arr[10];    
   example(arr);
   return 0;
}

输出:

0123456789

【问题讨论】:

  • arr[10] 未初始化

标签: c arrays printf


【解决方案1】:

这是错误的,会引发未定义的行为:

a[i] = i++;

没有为赋值、自增或索引操作符指定序列点,你不知道自增对i的影响何时发生。

看看Question 3.1 of C-FAQ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-13
    • 2017-05-21
    • 2019-11-14
    • 2014-02-08
    • 2022-07-06
    • 2022-08-13
    • 2019-12-12
    • 2018-01-29
    相关资源
    最近更新 更多