簡體   English   中英

處理輸入時意外凍結

[英]unexpected freeze while handling input

我一直在嘗試處理用戶可以選擇的多個功能,但是由於某些原因,意外的輸入不會引起開發的反應,而是凍結。

int main(){
    int done = 0, isModeValid = 1;
    char nextMode[15], *options[] = {"quit",  "test", "getASCII"};

    while(done == 0){
        cls();
        isModeValid = 0;
        text(1);
        currentOptions(options);
        gets(nextMode);
        int i = 0;
        for(i = 0; i < (sizeof(options)); i++){
            if(strcmp(nextMode, options[i]) == 0){
                 done = runMode(i);
                 break;
            }
            //Error seems to happen after this point
            if(strcmp(nextMode, options[i]) != 0 && i == sizeof(options)){
                cls();
                text(3);
                Sleep(750);
            }
        }
    }
    return 0;
}
void cls(){
    system("cls");
}

您正在調用未定義的行為。 sizeof產生參數的大小(以字節 / char單位),而不是數組的長度 因此,您要遍歷比數組實際包含的元素更多的元素,並嘗試訪問超出其邊界的元素。

使用sizeof(options) / sizeof(options[0])獲得獨立於每個條目類型的長度。

注意:聲明數組為static將在調用main之前對其進行分配和初始化。 您的當前版本將在每次調用該函數時執行該操作。 盡管對main並不重要,但對於不止一次被調用的其他功能而言,它卻具有重要意義。

要獲取options的數字字符串,您需要(sizeof(options)/sizeof(options[0])) ,而不僅僅是sizeof(options) ...因此,您的for循環循環了很多次,並且您正在訪問范圍。

另外,您的第二個命令if永遠不會執行,因為i永遠也不會進入sizeof(options)

暫無
暫無

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

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