簡體   English   中英

執行代碼時出現分段錯誤(核心轉儲)錯誤

[英]Getting a Segmentation fault (core dumped) error when I execute my code

我正在為我的 C 編程 class 做一個項目,一切正常,直到我在第 22 行添加了一個 while 循環,以便一遍又一遍地運行代碼以根據用戶輸入打印一個三角形。 代碼的第一次迭代仍然有效,但是當它接受輸入來確定如何更新代碼並再次運行它時,我得到一個段錯誤,我不明白為什么。 我的代碼如下:

#include <stdio.h>
#include <string.h>

int main() {
    int size = 0;
    char symbol = ' ';
    int i = 0;
    int space = 0;
    int n = 0;
    int oldSize = 0;
    char oldSymbol = ' ';
    char menuChoice = ' ';
    
    printf("Please enter the size of the triangle (2-40): ");
    scanf("%d", &size);
    printf("Please enter the character you would like to use: ");
    scanf(" %c", &symbol);
    
    oldSize = size;
    oldSymbol = symbol;
    
    while (menuChoice != 'Q' || menuChoice != 'q') {
        if (size < 2 || size > 40) {
            size = 5;
            symbol = '*';
            printf("Error: Size outside bounds. Printing default triangle: \n");
        }
        for(i = 1; i <= size + 1; ++i, n = 0) {
            for(space = 1; space <= size + 1 - i; ++space) {
                printf(" ");
            }
            while (n != i - 1) {
                printf("%c ", symbol);
                ++n;
            }
            printf("\n");
        }
    
        printf("G: Grow the current triangle\n");
        printf("S: Shrink the current triangle\n");
        printf("N: Draw a new triangle\n");
        printf("Q: Quit\n");
    
        scanf(" %c", menuChoice);
    
        if (menuChoice == 'G' || menuChoice == 'g') {
            size = size + 1;
            
        } else if (menuChoice == 'S' || menuChoice == 's') {
            size = size - 1;

        } else if (menuChoice == 'N' || menuChoice == 'n') {
            size = oldSize;
            symbol = oldSymbol;
            
        } else {
            printf("Error: please enter a valid argument.");
        }
    }
    printf("Goodbye");
}
scanf(" %c", menuChoice);

顯然是不正確的,並且您知道如何從您上傳的代碼中的其他地方調用它。 你要

scanf(" %c", &menuChoice);

我沒有發現任何其他類似的錯誤,並且這段代碼中沒有其他指針結構,所以應該到此結束。

暫無
暫無

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

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