【问题标题】:Program works on Dev-C++ but not on GCC程序适用于 Dev-C++ 但不适用于 GCC
【发布时间】:2011-02-13 13:39:30
【问题描述】:

大家好。我为在线比赛编写了这个程序。它在 Bloodshed 的 Dev-C++ 上运行良好,但在 GCC 上运行失败。本次大赛要求所有解决方案均基于GCC编译器。

它甚至不等待第二个输入。该程序在 Dev-C++ 上运行良好。请帮忙。

#include <stdio.h>

int testCases;

void runPgm()
{
    scanf("%d", &testCases);
    int array[testCases][2];
    char start[testCases];
    int i;
    for(i=0; i<testCases; i++)
    {
        scanf("%c %d %d", &start[i], &array[i][0], &array[i][1]);
    }
    for(i=0; i<testCases; i++)
    {
        printf("%c %d %d\n", start[i], array[i][0], array[i][1]);
    }
}

int main() {
    runPgm();
    return 0;
}

GCC 的输出:

machine:~$ cc prog.c -lm  
machine:~$ ./a.out  
2
a 3 3

 0 -1080493616
a 3 3
machine:~$

【问题讨论】:

  • 那么,您的程序是如何中断的?编译或运行时错误?
  • 运行时.. 等我添加输出..
  • fflush(stdin); 调用 UB BTW
  • 我刚刚添加了它..它甚至之前都不起作用..
  • 改进了描述并提供了可编译的源代码,以便人们进行测试。

标签: c gcc


【解决方案1】:

获取“testCases”后,使用“Enter”键,将“\n”添加到缓冲区中。

您应该使用 getchar() 将“\n”从缓冲区中取出。 for 循环中的 scanf 也一样

你的固定密码:

#include <stdio.h>
int testCases;


void runPgm()
{
    scanf("%d", &testCases);
    getchar();

    int array[testCases][2];
    char start[testCases];
    int i;
    for(i=0; i<testCases; i++)
    {
        scanf("%c %d %d", &start[i], &array[i][0], &array[i][1]);
        getchar();
    }
    for(i=0; i<testCases; i++)
    {
        printf("%c %d %d\n", start[i], array[i][0], array[i][1]);
    }
}

int main() {
    runPgm();
    return 0;
}

顺便说一句, 像你一样定义数组,不兼容 ANSI-C,我不确定为什么 gcc 可以接受。您应该为此目的使用动态分配(例如 malloc())

【讨论】:

  • 关于最后一段,它被C ANSI支持,被称为变长数组(VLA)。但是你/他应该通过参数将 testCases 传递给runPgm。不过 +1。
  • @jweyrich,他为什么以及如何将其作为参数传递?进入该功能时未知。我同意,尽管全局工作并不是最好的设计,但没有什么可以强迫这一点。
  • @Jens:因为标准要求在块的开头声明变量。由于扩展,GCC 允许它。只需将第一个scanf+getchar 移动到main,在函数原型中添加一个int 参数,并相应地传递它。或者,他可以将数组声明和以下代码包装在一个新块中。
  • @jweyrich,the 实际的 C 标准是 C99,自 12 年以来就已推出,它允许在首次使用之前在任何地方声明变量。顺便说一句,他将该变量声明为全局变量,这在 C 中一直是允许的。
  • @Jens:我指的是数组,而不是全局变量。是的,C ANSI = C99 = 实际标准。我一直认为混合代码和声明是一种扩展,但我只是检查了标准,我错了。很抱歉造成混乱:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 2017-01-11
相关资源
最近更新 更多