在简单程序中获取分段错误

时间:2016-06-02 18:16:18

标签: c segmentation-fault scanf

我在学校放假期间一直在教自己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;
}

2 个答案:

答案 0 :(得分:1)

您需要更改

scanf("%d", numberOne);

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

同样。

答案 1 :(得分:1)

SELECT *
FROM   USER u
JOIN   organization o
ON     u.organization_id = o.id
WHERE  u.uid NOT IN SELECT  * (
       (
            SELECT DISTINCT user_id
            FROM            web_request )
union
      (
            SELECT DISTINCT user_id
            FROM            user_milestone) ) AS t

因此,在所有scanf("%d", numberOne); ^ %d expects int * not int 语句中传递int变量的地址。