segmentation fault in C during scanf

2019-01-20 20:54发布

问题:

I am trying to scan in an integer to use for my program. However my program gives me segmentation fault during compilation this is the section that is giving me the error:

int main(void)
{
    int totalHeight=0, floorWidth=0, amountOfStories, amountWindowForTop, amountWindowForMiddle, amountWindowForBottom, windowHeight, middleWindowWidth, topWindowWidth, bottomWindowWidth, minimumHeight, minimumWidth;

    char topFloorWindowContent, middleFloorWindowContent, bottomFloorWindowContent, windowBorder, floorBorder;

    int tempMax;

    printf("please enter how many stories your building would like to have: ");
    scanf("%d",&amountOfStories);
    minimumHeight=amountOfStories*6+1;
    while((totalHeight<minimumHeight)||((totalHeight%amountOfStories)!=1))
    {
        printf("please enter the totalHeight (minimum %d): ",minimumHeight);
        scanf("%d",&totalHeight);
    }
    printf("please enter how many window building would have for top floor: ");
    scanf("%d",amountWindowForTop);
    printf("please enter how many window building would have for middle floors: ");

now my program after compile only runs to the scanf on the amoutWindowForTop after I enter in the value for that it just gives me segmentation fault I have no idea why. Because I am not using pointers so why is it giving me that error?everything seemed in order for me this is the output

please enter how many stories your building would like to have: 5
please enter the totalHeight (minimum 31): 31
please enter how many window building would have for top floor: 2
Segmentation fault

回答1:

You missed &,

Line

scanf("%d",amountWindowForTop);

should be

scanf("%d", &amountWindowForTop);
//---------^


回答2:

You missed & in

scanf("%d",amountWindowForTop);

this must be

scanf("%d",&amountWindowForTop);

Cause of error is & is called address of operator so missing it in scanf means where are you put your value means address is required because it specify the address of variable where we have to keep the value. segmentation fault error is generally we get whenever their is any problem related with address. Hope useful for you.



回答3:

You missed & in

 scanf("%d", amountWindowForTop);  
            ^Place & operator 


回答4:

You are missing the &

scanf("%d",&amountWindowForTop);
           ^