简体   繁体   中英

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

EDIT: solved it, turns out I should use %c not %s because foodSelect and foodSize are characters not strings :P thanks

I'm trying to pass 3 values to the function output : foodChoice, foodSelect, foodSize (and foodOrderNum, and foodSubtotal but I haven't gotten around to that yet).

However, when I try to printf foodSelec t, I get a segmentation fault, but when I try to print foodChoice , I don't. When I try to printf foodSize it just shows nothing.

source:

#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");


}

You haven't allocated memory for:

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

Do malloc and allocate memory. Note that:

char *foodChoice="Fish";

And

char *foodChoice;
foodChoice="Fish";

are not the same.

This is because you pass &foodSelect to scanf , which is incorrect for C strings. You should pass foodSelect instead, no ampersand.

You should also allocate sufficient space to store the values the users enter, and instruct scanf on the max size of the buffer.

#define MAX_BUF 128

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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