Tianyou Hu
Tianyou Hu

Reputation: 1

multiple scanf in a program causing crash in c?

#include <stdio.h>

int main()
{       
    printf("how old are you? ");
    int age = 0;
    scanf("%d", age);

    printf("how much does your daily habit cost per day? \n");
    int daily = 0;
    scanf("%d", daily); 

    double thisyear = daily * 365;

    printf("\n");
    printf("this year your habit will cost you: %.2f", thisyear);

    return 0;
}

this is my program for school, when i write this i am trying get the user to 1, give their age and 2, their daily cost of living. however my program would crash when i run this

Upvotes: 0

Views: 550

Answers (3)

selbie
selbie

Reputation: 104559

The scanf function expects a pointer.

scanf("%d", &age);

Ditto for the line where you scanf on "daily".

Upvotes: 1

Levon
Levon

Reputation: 143082

scanf("%d", daily);

needs to become

scanf("%d", &daily);

You need to pass the address of the variable (i.e., a pointer, this is done with the &) to scanf so that the value of the variable can be changed. The same applies for your other prompt. Change it to

scanf("%d", &age);

Now you should get this when you run your program:

% a.out
how old are you? 30
how much does your daily habit cost per day? 
20

this year your habit will cost you: 7300.00

Upvotes: 3

JoseP
JoseP

Reputation: 641

scanf works with references to variables

printf("how old are you? ");
int age = 0;
scanf("%d", &age);

printf("how much does your daily habit cost per day? \n");
int daily = 0;
scanf("%d", &daily); 

double thisyear = daily * 365;

printf("\n");
printf("this year your habit will cost you: %.2f", thisyear);

Upvotes: 0

Related Questions