c - 程序可以在 Dev-C++ 上运行,但不能在 GCC 上运行

标签 c gcc

大家好。我为在线竞赛编写了这个程序。它在 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:~$

最佳答案

获取“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 - 程序可以在 Dev-C++ 上运行,但不能在 GCC 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4984446/

相关文章:

c - 如何创建 128 位变量并将其从 Chapel 程序传递到第三方 C 库?

python - 使用 swig 将 c++ 编译为 python

c++ - 将目录传递给 g++ 以包含文件的正确标志

c - 尝试将结构传递给函数时保持段错误

gcc - 在 Windows 中静态链接 GTK+ 库

c++ - g++ __thread = 非平凡的构造函数

c - 堆排序无法正常工作

c++ - vector 排序和更改数据

c - strtof() 在 C 中产生奇怪的结果

c - 代理 DNS 未收到响应