簡體   English   中英

我的代碼在 VSCode 中運行,但不在 DevC 中運行

[英]My code runs in VSCode but does not run in DevC

#include <stdlib.h>
#include <stdio.h>

void arraydescending(int array[]){
    for (int j=0; j<9; j++){
        for (int i=0; i<8; i++)
        {
            if(array[i]<array[i+1]){
            int swapper = array[i+1];
            array[i+1]=array[i];
            array[i]=swapper;
            }
        }
    }
    for (int c=0; c<9; c++){
        printf("%d",array[c]);
    }
}

void arrayreverse(int array[])
{
    for(int i = 0; i<4; i++)
    {
        int swapper = array[i];
        array[i] = array[8-i];
        array[8-i] = swapper;
    }
    for (int c=0; c<9; c++){
        printf("%d",array[c]);
    }
}

int main()
{
    int choice;
    printf("Please enter your choice:");
    scanf("%d", &choice);
    if(choice == 1)
    {
        int mynumberarray[9] = {1,1,0,2,0,0,0,4,7};
        int choice_2;
        printf("Write 1 for reverse order, write 2 for descending order:");
        scanf("%d", &choice_2);
        if(choice_2 == 1)
        {
            arrayreverse(mynumberarray);
        }
        else if(choice_2 == 2)
        {
            arraydescending(mynumberarray);
        }
        else
        {
            printf("Invalid choice");
        }
    }
    else if(choice == 2){
        int userarray[9];
        char * user_entry;
        printf("Please enter your school no (9 digits):");
        scanf("%s",user_entry);
        for(int i = 0; i < 9; i++)
        {
            userarray[i] = user_entry[i] - '0';
        }
        int choice_2;
        printf("Write 1 for reverse order, write 2 for descending order:");
        scanf("%d", &choice_2);
        if(choice_2 == 1)
        {
            arrayreverse(userarray);
        }
        else if(choice_2 == 2)
        {
            arraydescending(userarray);
        }
        else
        {
            printf("Invalid choice");
        }
    }
    else
    {
        printf("Invalid choice");
    }
    return 0;
}

當我使用 gcc -std=c99; 編譯它時,此代碼運行正確但是我的朋友有 DevC 5.11 版本可以編譯代碼,但它在他的 DevC 中無法正確運行(它在第二個 scanf 中退出程序)。 兩者都可以編譯,但為什么它不能在 DevC 5.11 中使用編譯器 gcc 4.9.2 運行? 我正在等待您的建議,因為我不明白它背后的原因,我的代碼看起來沒有任何錯誤。

您的程序至少有未定義的行為,因為在此代碼段中

    char * user_entry;
    printf("Please enter your school no (9 digits):");
    scanf("%s",user_entry)

您正在使用具有不確定值的未初始化指針user_entry 您需要聲明一個足夠大的字符數組,您將在其中讀取一串數字。 不要忘記在數組中為讀取字符串的終止零字符保留一個空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM