gpt4 book ai didi

c - 使用字符串、指针和函数在 C 中获取段错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:58 25 4
gpt4 key购买 nike

编辑:解决了,结果我应该使用 %c %s 因为foodSelect 和 foodSize 是字符而不是字符串:P 谢谢

我正在尝试将 3 个值传递给函数 output:foodChoice、foodSelect、foodSize(以及 foodOrderNum 和 foodSubtotal,但我还没有解决这个问题)。

但是,当我尝试 printf foodSelect 时,出现了段错误,但是当我尝试打印 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");


}

最佳答案

你还没有分配内存:

字符*食物选项;炭*食物选择;字符*食物选择;字符 *foodSize;

malloc并分配内存。请注意:

char *foodChoice="Fish";

char *foodChoice;
foodChoice="Fish";

不一样。

关于c - 使用字符串、指针和函数在 C 中获取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9878539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com