【问题标题】:I keep getting a segmentation fault in my C code我的 C 代码中不断出现分段错误
【发布时间】:2020-09-02 07:26:46
【问题描述】:

首先,我对 C 编程比较陌生,想编写一个能够接受用户输入然后将其传递给 switch/case 并根据初始选择返回输出的程序。我可以在使用 int 数据类型时做到这一点,但我希望在将输入作为 char 时得到一些帮助。

#include <stdio.h>

double x = 1;
double y = 3;
char inputLet[1];

double chooseEquation(char notLet){
    char notNotLet = notLet;
    printf("notLet here is: %c \n", notLet);
    switch(notLet){
        case 'A':
            x += y;
            printf("Case1 reached! \n");
            break;
        case '2':
            x += -y;
            break;
        case '3':
            x -= y;
            break;
        case '4':
            x -= -y;
            break;
        case '5':
            x *= y;
            break;
        case '6':
            x *= -y;
            break;
        default :
        printf("defaulting! btw: %c \n", notNotLet);
        x = 0;
    }
    printf("x has been set? Here: %.2f\n", x);
    return x;
}

int main(){
    printf("Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation: \n");
    scanf(" %c", &inputLet);
    printf("The letter you chose is: %s \n", inputLet);
    double outputLet = chooseEquation(inputLet);
    printf("Your equation evaluated to: %.2f \n", outputLet);
    return 0;
}


不知怎么的,不管输入什么,开关看的字符都变成了Q

但是,如果我替换这一行: char inputLet[1];

用这一行: char inputLet;

程序分段错误。

任何帮助将不胜感激。

【问题讨论】:

  • %c 是单个 char 的说明符,%s 是空终止 char 数组的说明符。不要混合它们,它们使用不同的类型
  • 并且double outputLet = chooseEquation(inputLet); 行至少应该给出编译器警告,因为您传递的是char*,而函数需要char
  • @UnholySheep 好吧,这就是为什么我提到我的编辑,我删除了应该使其成为单个 char 数据类型的 [1],然后导致上述分段错误。
  • 向您说明的一点是printf("The letter you chose is: %s \n", inputLet); 是错误的,因为%s 需要一个字符串。 inputLet 是单个字符数组,它不是字符串(因为它不是以 NULL 结尾的序列)。
  • 如果你从声明中删除[1],那么printf("The letter you chose is: %s \n", inputLet); 应该会抱怨——因为你在这里有%s 而不是%c

标签: c input types


【解决方案1】:
printf("The letter you chose is: %s \n", inputLet);

当您使用char inputLet 时,请使用%c。这是导致错误的原因。

如果它是单个字符,那么只需使用 char inputLet 而不是字符数组。

更改后,我在本地对其进行了测试,得到了 'A' 的输出

Welcome, please pick a letter from A to F (uppercase for now) in order to choose an equation: 
A
HelloThe letter you chose is: A 
notLet here is: A 
Case1 reached! 
x has been set? Here: 4.00
Your equation evaluated to: 4.00 

【讨论】:

  • 有趣的是,如果 scanf 使用 %c 它只会输入输入的第一个字符并且不会附加空终止符。每天学习新东西:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 2015-06-22
  • 2019-06-16
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
相关资源
最近更新 更多