开发者

Program works on Dev-C++ but not on GCC

开发者 https://www.devze.com 2023-02-10 00:46 出处:网络
Hey all. I wrote this program for an online contest. It RUNS FINE on Bloodshed\'s Dev-C++ but it breaks down with GCC. The contest demands all solutions based on GCC compiler.

Hey all. I wrote this program for an online contest. It RUNS FINE on Bloodshed's Dev-C++ but it breaks down with GCC. The contest demands all solutions based on GCC compiler.

It doesn't even wait for the 2nd input. The program worked fine on Dev-C++. Please, help.

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

Output with GC开发者_高级运维C:

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

 0 -1080493616
a 3 3
machine:~$


After getting "testCases", you use the "Enter" key, which adds "\n" to the buffer.

You should use getchar() to get the "\n" out of the buffer. same thing for the scanf in the for loop

Your fixed code:

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

BTW, defining arrays like you did, is not ANSI-C compatible, and I am not sure why gcc is ok with this. You should use dynamic allocation for that purpose (like malloc())

0

精彩评论

暂无评论...
验证码 换一张
取 消