【问题标题】:Getting segmentation fault in simple program在简单程序中出现分段错误
【发布时间】:2016-06-02 18:16:17
【问题描述】:

我在学校放假期间一直在自学 C,最近尝试编写一个简单的计算器程序,它应该接受两个整数并对它们执行四种操作之一 (+-*/),但只要第一个变量已分配我收到分段错误/核心转储错误消息。我知道这与内存分配有关,并且我尝试过使用指针和 malloc,但我怀疑我这样做不正确。

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

int calculate(int numberOne, int numberTwo, int operator);

int main(){

//Declaring Variables
int numberOne, numberTwo, total, operator;
int *one, *two, *tot, *op;


//Assigning Variables
printf("Integer 1: ");
scanf("%d", numberOne);
printf("\nOperator 1[+] 2[-] 3[*] 4[/] : ");
scanf("%d", operator);
printf("Integer 2: ");
scanf("\n%d", numberTwo);


//Output Calculatoin Through Function
printf("Calculation Complete: %d is the answer", calculate(numberOne, numberTwo, operator));
}

int calculate(int numberOne, int numberTwo, int operator) {

int total = 0;
do{
    switch(operator){

        case 1:
            total = numberOne + numberTwo;
            break;

        case 2:
            total = numberOne - numberTwo;
            break;

        case 3:
            total = numberOne*numberTwo;
            break;

        case 4:
            total = numberOne/numberTwo;
            break;          

        default:
            printf("Error, Invalid Operator, Please Enter A New One: ");
            scanf("%d", operator);
        }
}while(total ==0);

return total;
}

【问题讨论】:

  • 干杯,伙计们,我完全忘记了我必须传递地址而不是值
  • 与以往一样,请启用编译器警告,这 (MSVC) 会给出 “警告 C4700:使用未初始化的局部变量 'numberOne'”

标签: c segmentation-fault scanf


【解决方案1】:

你需要改变

scanf("%d", numberOne);

scanf("%d", &numberOne);   //%d expects a pointer to int argument

同样如此。

【讨论】:

    【解决方案2】:
    scanf("%d", numberOne);
               ^ %d expects int * not int 
    

    所以在所有scanf 语句中传递int 变量的地址。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多