繁体   English   中英

编译C文件没问题,但exe文件什么也不显示

[英]Compiling C file is fine, but exe file displays nothing

我一直试图弄清楚发生了什么,但这让我发疯。 我在这里有这个脚本,它编译得很好(我正在使用 GCC),但是当我尝试运行编译的 exe 时,终端会暂停片刻并退出。 我不知道发生了什么,任何帮助将不胜感激。

// not sure what's on
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "extra.h"
int RanNum(int StartNum, int StopNum);
int main() {
    printf("Hey\n");
    int magicNum, guess, choice;
    do {
        printf("Guess the right number: ");
        scanf("%d", &choice);
        guess = 1;
        magicNum = RanNum(3,10);
        if (choice == magicNum){
            printf("You win! \n");
            break;
        } else {
            int rem = (3 - guess);
            printf("\nYou have %d tries remaining \n", rem);
        }
        guess++;
    } while (guess <= 3);
    if (guess > 3) {        
        printf("You lost... We can try again...\n");
    }
    return 0;
}

int RanNum(int StartNum, int StopNum){  
    int *list;
    int Divided;
    int range = StartNum - StopNum;
    int RandArray[range];
    for (int i=StartNum; i<StopNum; i++) {
        for (int j=0; j<range+1; j++) {
            RandArray[j] = i;
        }
    }
    list = RandArray;
    Divided = (StartNum+StopNum)/range;
    return list[Divided];   
}
  • RanNum遇到 UB(未定义行为),无声退出是 UB 的一种可能表现。

     int RanNum(int StartNum, int StopNum){ // <---- called with StartNum = 3, StopNum = 10 int *list; int Divided; int range = StartNum - StopNum; // <---- range = 3 - 10 = -7 int RandArray[range]; // <---- array of negative size *** UB for (int i=StartNum; i<StopNum; i++) { for (int j=0; j<range+1; j++) { // <---- after 'range' is fixed to be > 0 RandArray[j] = i; // <---- the last iteration j = range } // <---- overruns the array bound *** UB } // ... }
  • 一旦第一个问题得到解决, main循环就会出现另一个问题。

     int magicNum, guess, choice; // <---- 'guess' is defined but not initialized do { printf("Guess the right number: "); scanf("%d", &choice); guess = 1; // <---- 'guess' is initialized to '1` in each iteration /* code that does not change or use 'guess' */ guess++; // <---- 'guess' was '1' and is now incremented to '2' } while (guess <= 3); // <---- always true, so loop continues until number guessed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM