簡體   English   中英

使用字符串,指針和函數在C中獲取分段錯誤

[英]Getting a segmentation fault in C with usage of strings, pointers, and functions

編輯:解決了它,原來我應該使用 %c 而不是 %s 因為foodSelect和foodSize是不是字符串的字符:P謝謝

我試圖將3個值傳遞給函數output :foodChoice,foodSelect,foodSize(以及foodOrderNum和foodSubtotal,但我還沒有解決這個問題)。

但是,當我嘗試foodSelec t時,出現了段錯誤,但是當我嘗試打印foodChoice ,卻沒有。 當我嘗試printf foodSize它什么也沒顯示。

資源:

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

void question (char choice[]);
int output(char *foodChoice, char *foodSelect, char *foodSize);


void question (char choice[]) {

    char choiceYesNo;
    char *foodOptions;
    char *foodChoice;
    char *foodSelect;
    char *foodSize;
    int foodOrderNum = 0;
    float foodSubtotal = 0;

    switch (choice[0]) {
        case 'f':
            foodChoice = "Fish";
            foodOptions = "(K- Haddock, T- Halibut)";
            break;
        case 'c':
            foodChoice = "Chips";
            foodOptions = "(C- Cut, R- Ring)";
            break;
        case 'd':
            foodChoice = "Drinks";
            foodOptions = "(S- Softdrink, C- Coffee, T- Tea)";
            break;
    }

    printf("Do you order %s? (Y/N): ", foodChoice);
        scanf("%c", &choiceYesNo);
    printf("%s choice %s: ", foodChoice, foodOptions);
        scanf("%s", &foodSelect);
    printf("What size (L - Large, M - Medium, S - Small): ");
        scanf("%s", &foodSize);
    printf("How many orders do you want? (>=0): ");
        scanf("%d", &foodOrderNum);
    output(foodChoice, foodSelect, foodSize);
}

int output(char *foodChoice, char *foodSelect, char *foodSize) {

    // printf("You ordered %s: %s - SIZE: %s   amount ordered: , subtotal price: \n", 
    // foodChoice, foodSelect, foodSize);

    printf("\n\n%s\n", foodSelect);
    // printf("\n\n%s\n", foodSelect);

}

int main() {

    question("chips");


}

您尚未為以下項分配內存:

char * foodOptions; char * foodChoice; char * foodSelect; char * foodSize;

執行malloc並分配內存。 注意:

char *foodChoice="Fish";

char *foodChoice;
foodChoice="Fish";

不一樣。

這是因為您將&foodSelect傳遞給scanf ,這對於C字符串是不正確的。 您應該通過foodSelect代替,不要使用&號。

您還應該分配足夠的空間來存儲用戶輸入的值,並指示scanf有關緩沖區的最大大小。

#define MAX_BUF 128

...
char foodSelect[MAX_BUF];
...
scanf("%127s", foodSelect);

暫無
暫無

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

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